| Python Language Reference Manual by Guido van Rossum and Fred L. Drake, Jr. Paperback (6"x9"), 120 pages ISBN 0954161785 RRP £12.95 ($19.95) Sales of this book support the Python Software Foundation! Get a printed copy>>> |
7.5 The with statement
The with statement, added in version 2.5, is used to wrap the execution of a block
with methods defined by a context manager (see
section 3.4.9). This allows common
try ... except ... finally usage patterns to
be encapsulated for convenient reuse.
with_stmt "with"expression["as" target] ":"suite
The execution of the with statement proceeds as follows:
- The context expression is evaluated to obtain a context manager.
-
The context manager's
__enter__()method is invoked. -
If a target was included in the
withstatement, the return value from__enter__()is assigned to it. Note: Thewithstatement guarantees that if the__enter__()method returns without an error, then__exit__()will always be called. Thus, if an error occurs during the assignment to the target list, it will be treated the same as an error occurring within the suite would be. See step 5 below. - The suite is executed.
-
The context manager's
__exit__()method is invoked. If an exception caused the suite to be exited, its type, value, and traceback are passed as arguments to__exit__(). Otherwise, threeNonearguments are supplied. If the suite was exited due to an exception, and the return value from the__exit__()method was false, the exception is reraised. If the return value was true, the exception is suppressed, and execution continues with the statement following thewithstatement. If the suite was exited for any reason other than an exception, the return value from__exit__()is ignored, and execution proceeds at the normal location for the kind of exit that was taken.
Notice:
In Python 2.5, the with statement is only allowed
when the with_statement feature has been enabled. It will always
be enabled in Python 2.6. This __future__ import statement can
be used to enable the feature:
from __future__ import with_statement
See also:
- PEP0343 The "with" statement
-
The specification, background, and examples for the Python
withstatement.
| ISBN 0954161785 | Python Language Reference Manual | See the print edition |