Skip to content
Tutorials Center
My learning

Topics

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.

Python
with open("data.txt") as f:
    text = f.read()
# the file is closed here, even after an error

Try it

Python A class-based context manager

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.

Python contextlib helpers

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

Python
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 or continues, __exit__() is called.
  • Return False (or None) from __exit__ unless you really mean to swallow the error. Swallowing exceptions silently hides bugs; contextlib.suppress makes the intent explicit.
  • The as value is whatever __enter__() returned, not necessarily the manager itself. open() returns the file, a database connection manager may return a cursor.
  • @contextmanager generators must yield exactly once. Wrap the yield in try/finally so cleanup runs when the block raises; the exception is re-raised at the yield.
  • 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).
  • ExitStack handles a dynamic number of managers and registers arbitrary cleanup callbacks.
  • Async version. async with uses __aenter__() and __aexit__().