Python Reference ยท Statements and Keywords
Python context managers
Reference for Python context managers: the with statement protocol, __enter__ and __exit__, suppressing exceptions, contextlib helpers and ExitStack.
A context manager is an object that sets something up when a block starts and cleans it up when the block ends, even if an exception interrupts it. You use one with the with statement: files, locks, database transactions and temporary settings are typical examples.
The protocol has two methods, __enter__() and __exit__(). You can implement them in a class, or write a generator function and turn it into a context manager with contextlib.contextmanager.
with open("data.txt") as f: text = f.read() # the file is closed here, even after an error
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
with expression as target: block with a() as x, b() as y: block with ( a() as x, b() as y, ): block
| Method | Description |
|---|---|
__enter__(self) |
Runs on entry. Its return value is bound to the name after as. |
__exit__(self, exc_type, exc, tb) |
Runs on exit. The three arguments are None if the block finished normally. A true return value suppresses the exception. |
Order: expression is evaluated, __enter__() is called, the block runs, then __exit__() is called. With several managers, they are exited in reverse order.
Raises: anything raised by the block or by __exit__(). If __exit__() returns a false value, the original exception continues.
Usage notes
- Cleanup always runs. Whether the block finishes, raises, returns,
breaks orcontinues,__exit__()is called. - Return
False(orNone) from__exit__unless you really mean to swallow the error. Swallowing exceptions silently hides bugs;contextlib.suppressmakes the intent explicit. - The
asvalue is whatever__enter__()returned, not necessarily the manager itself.open()returns the file, a database connection manager may return a cursor. @contextmanagergenerators mustyieldexactly once. Wrap theyieldintry/finallyso cleanup runs when the block raises; the exception is re-raised at theyield.- Reusable or not. Many managers, such as file objects and generator-based ones, can be used only once. Check the documentation before reusing an instance.
- Parenthesized form of multiple managers is official since Python 3.10 (it worked unofficially in 3.9).
ExitStackhandles a dynamic number of managers and registers arbitrary cleanup callbacks.- Async version.
async withuses__aenter__()and__aexit__().
Related
with,__enter__() and __exit__(),open(),contextlibtry- Lessons: Context managers, Files