We're back after a server migration that caused effbot.org to fall over a bit harder than expected. Expect some glitches.

With Statement Contexts and Context Managers

New in version 2.5.

A context manager (or context guard) is an object that defines the runtime context to be established when executing a with statement. The context manager provides a with statement context object which manages 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 the with statement, but can also be used by directly invoking their methods.

Typical uses of context managers and contexts include saving and restoring various kinds of global state, locking and unlocking resources, closing opened files, etc.

For more information on context managers and context objects, see “[Context Types][2]” in the [Python Library Reference][3].

See Also:

PEP 0343, The “with” statement The specification, background, and examples for the Python with statement.