Jun 28, 2011

with statement in Python

learning python 4th edition p851

with expression [as variable]:
with-block


with 类似于
try
finally
不过更简洁

Here’s how the with statement actually works:
1. The expression is evaluated, resulting in an object known as a context manager that
must have __enter__ and __exit__ methods.
2. The context manager’s __enter__ method is called. The value it returns is assigned
to the variable in the as clause if present, or simply discarded otherwise.
3. The code in the nested with block is executed.
4. If the with block raises an exception, the __exit__(type, value, traceback) method
is called with the exception details. Note that these are the same values returned
by sys.exc_info, described in the Python manuals and later in this part of the book.
If this method returns a false value, the exception is reraised; otherwise, the exception
is terminated. The exception should normally be reraised so that it is
propagated outside the with statement.
5. If the with block does not raise an exception, the __exit__ method is still called,
but its type, value, and traceback arguments are all passed in as None.

expression 可以是一个context manager对象,则使用同一个对象,比如在threading时,lock是一个context manager,所有线程都使用同一个lock。如果是返回这类对象的语句,则每次都生成一个新的对象

0 comments: