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]” in the [Python Library Reference].