|Python Language Reference Manual|
by Guido van Rossum and Fred L. Drake, Jr.
Paperback (6"x9"), 120 pages
RRP £12.95 ($19.95)
Sales of this book support the Python Software Foundation! Get a printed copy>>>
3.4.9 With Statement Context Managers
Added in version 2.5, a context manager is an object that defines the runtime
context to be established when executing a
statement. The context manager handles the entry into,
and the exit from, the desired runtime context for the execution
of the block of code. Context managers are normally invoked using
with statement (described in section 7.5), but
can also be used by directly invoking their methods.
Typical uses of context managers include saving and restoring various kinds of global state, locking and unlocking resources, closing opened files, etc.
For more information on context managers, see "Context Types" in the Python Library Reference Manual.
Enter the runtime context related to this object. The
withstatement will bind this method's return value to the target(s) specified in the
asclause of the statement, if any.
__exit__(self, exc_type, exc_value, traceback)
Exit the runtime context related to this object. The parameters
describe the exception that caused the context to be exited. If
the context was exited without an exception, all three arguments
None. If an exception is supplied, and the method wishes to suppress the exception (i.e., prevent it from being propagated), it should return a true value. Otherwise, the exception will be processed normally upon exit from this method. Note that
__exit__methods should not reraise the passed-in exception; this is the caller's responsibility.
- PEP0343 The "with" statement
The specification, background, and examples for the Python
|ISBN 0954161785||Python Language Reference Manual||See the print edition|