Search notes:

Python: context manager

A context manager is an object that is meant to manage allocation and freeing of resources. Such objects are able to be used in conjunction with the with statement.
A context manager needs to implement the __enter__ and __exit__ methods.

Typical example

A typical example for a context manager is using open() together with a with statement like so:
with open('foo.txt') as f:
     text = f.read()
When the with block is exited, the context manager automatically calls the f.close().

See also

contextmanager (in the standard library contextlib) is a decorator that turns a function into a context manager.

Index