Understanding with… in Python... As... Syntax

Source: Internet
Author: User

Understanding with… in Python... As... Syntax

To solve this problem, open the file:

try:    f = open('xxx')    do somethingexcept:    do somethingfinally:    f.close()

In fact, I personally read this on the Internet more than once. This is wrong.
First, it is correct as follows:

try: f = open('xxx')except: print 'fail to open' exit(-1)try: do somethingexcept: do somethingfinally: f.close()

It's troublesome, isn't it? But the correct method is to write it like this.

The reason why we want to write finally is that the file cannot be closed after the program throws an exception, but the premise is that the file has been opened.

In the first error code, if the exception occurs when f = open ('xxx'), for example, the file does not exist, you can immediately know that the execution of f. close () is meaningless. The solution after correction is the second code.

Now let's start to discuss the with syntax.

First, let's start with the following question: try-finally syntax structure:

set things uptry: do somethingfinally: tear things down

This is a common structure. For example, if a file is opened, set things up indicates f = open ('xxx'), and tear things down indicates f. close (). Such as multi-threaded locks and resource requests, there is a demand for release. Try... The finally structure ensures that the tear things down section will always be executed, even if the above do something work is not fully executed.

That is to say, with is a control flow statement, which is similar to if/for/while/try. with can be used to simplify try finally code and it looks clearer than try finally.
Here, a new "context management protocol" context management protocol "is introduced. The implementation method is to define two functions for a class: _ enter _ and _ exit.

with expresion as variable

First, execute the _ enter _ function. Its return value is assigned to the variable after the as function, as long as you know how to handle it, if you do not write as variable, the return value will be ignored.

Then, start to execute the statements in with-block, regardless of the success or failure (such as exceptions or errors, set sys. exit (). After the with-block operation is complete, the _ exit _ function is executed.
This process is equivalent:

Try: Execute the content of _ enter _ and execute with_block. finally: Execute the content of _ exit _.

The final solution of the python-dev team. (The with expression syntax is added after python 2.5)

class controlled_execution: def __enter__(self): set things up return thing def __exit__(self, type, value, traceback): tear things downwith controlled_execution() as thing: do something

However, some code is encapsulated into the _ enter _ function, and the cleanup code is encapsulated into the _ exit _ function.

We can implement an example by ourselves:

import sys class test: def __enter__(self): print("enter") return 1 def __exit__(self,*args): print("exit") return True with test() as t: print("t is not the result of test(), it is __enter__ returned") print("t is 1, yes, it is {0}".format(t)) raise NameError("Hi there") sys.exit() print("Never here") 

Here, python uses the with-as syntax. When python executes this sentence, it calls the _ enter _ function and passes the return value of the function to the variable specified after the as operation. Then, python will execute the following do something statement block. Finally, no matter What exception occurs in the statement block, it will execute _ exit _ when leaving __.
In addition to tear things down, you can also monitor and handle exceptions. Pay attention to the following parameters. To skip an exception, you only need to return the True function. The following sample code skips all typeerrors and throws other exceptions.

def __exit__(self, type, value, traceback): return isinstance(value, TypeError)

After python2.5 and later, the _ enter _ and _ exit _ functions have been written for the file object. We can test the function as follows:

>>> f = open("x.txt")>>> f  >>> f.__enter__()  >>> f.read(1)'X'>>> f.__exit__(None, None, None)>>> f.read(1)Traceback (most recent call last): File "  ", line 1, in  ValueError: I/O operation on closed file    

If we want to open the file and make sure to close it at last, we only need to do this:

with open("x.txt") as f: data = f.read() do something with data

If there are multiple items, we can write as follows:

with open("x.txt") as f1, open('xxx.txt') as f2: do something with f1,f2

As mentioned above, the _ exit _ function can handle some exceptions. If we do not handle exceptions in this function, it will throw normally, at this time, we can write it like this (python 2.7 and later versions. For earlier versions, see use contextlib. nested library function ):

try: with open( "a.txt" ) as f : do somethingexcept xxxError: do something about exception

In short, the with-as expression greatly simplifies finally writing every time, which is of great help to keep the code elegant.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.