# Python with语句用法

With语句是什么？
Python’s with statement provides a very convenient way of dealing with the situation where you have to do a setup and teardown to make something happen. A very good example for this is the situation where you want to gain a handler to a file, read data from the file and the close the file handler.

Without the with statement, one would write something along the lines of:

as file:    data = file.read()with如何工作？
while this might look like magic, the way Python handles with is more clever than magic. The basic idea is that the statement after with has to evaluate an object that responds to an __enter__() as well as an __exit__() function.

After the statement that follows with is evaluated, the __enter__() function on the resulting object is called. The value returned by this function is assigned to the variable following as. After every statement in the block is evaluated, the __exit__() function is called.

This can be demonstrated with the following example:

python#
with_example01.py  class Sample:    def __enter__(self):        print "In
__enter__()"        return "Foo"     def __exit__(self, type,
value, trace):        print "In
__exit__()"  def get_sample():    return Sample()  with
get_sample() as sample:    print "sample:",
sampleWhen executed, this will result in:

./with_example02.pytype:
<type 'exceptions.ZeroDivisionError'>value:
integer division or modulo
by zerotrace:
<traceback object at 0x1004a8128>Traceback
(most recent call last):  File "./with_example02.py",
line 19, in <module>    sample.do_something()  File "./with_example02.py",
line 15, in do_something    bar = 1/0ZeroDivisionError:
integer division or modulo
by zeroEssentially, if there are exceptions being thrown from anywhere inside the block, the __exit__() function for the object is called. As you can see, the type, value and the stack trace associated with the exception thrown is passed to this function. In this case, you can see that there was a ZeroDivisionError exception being thrown. People implementing libraries can write code that clean up resources, close files etc. in their __exit__() functions.

Thus, Python’s with is a nifty construct that makes code a little less verbose and makes cleaning up during exceptions a bit easier.

I have put the code examples given here on Github.