A python context manager manages the context of a with statement. A context manager defines enter and exit hooks that get called as the code block under the with statement is entered and exited, respectively.
Python’s with-statement creates a runtime context, defined by a context manager. As the code block under the with
statement is entered, a __enter__
hook is called on the context manager, and as it is exited (by any means, including exceptions and return statements), the __exit__
hook is called.
Python provides several standard context managers. File objects, for example, can be opened as a context manager, and on exit the file is automatically closed.
Context managers were defined in PEP 343.