Python Reference ยท Standard Library: Data Structures and Functional Tools
The contextlib module
Reference for Python's contextlib module: @contextmanager, suppress, closing, redirect_stdout, ExitStack, nullcontext and async context managers.
The contextlib module makes with statements easier to build and use. Writing a context manager by hand means a class with __enter__ and __exit__; contextlib lets you write the same thing as a short generator function, silence expected exceptions in one line, capture printed output, and manage a variable number of resources.
The most important tool is the @contextmanager decorator. Everything before yield runs on entering the with block, the yielded value becomes the as target, and everything after yield runs on exit. Wrap the yield in try/finally so the cleanup runs even if the block raises.
from contextlib import contextmanager @contextmanager def tag(name): print(f"<{name}>") try: yield finally: print(f"</{name}>")
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.
What is in the module
| Name | Description |
|---|---|
@contextmanager |
Turns a generator function with one yield into a context manager factory. |
@asynccontextmanager |
The same for async with, using an async generator. |
suppress(*exceptions) |
Ignores the listed exception types raised inside the block, then continues after it. |
closing(thing) |
Calls thing.close() on exit; for objects with close() but no context manager support. |
redirect_stdout(target), redirect_stderr(target) |
Temporarily send sys.stdout or sys.stderr to a file-like object. |
nullcontext(value=None) |
Does nothing; yields value. Handy for optional context managers. |
ExitStack(), AsyncExitStack() |
Collects any number of context managers and callbacks and unwinds them in reverse order. |
ContextDecorator |
Base class that lets a context manager also work as a function decorator. |
chdir(path) |
Temporarily changes the working directory (3.11). |
aclosing(thing) |
Calls await thing.aclose() on exit (3.10). |
@contextmanager returns: a function that, when called, returns an object usable in with.
Raises: RuntimeError if the generator yields more than once or never yields.
Usage notes
- Use
try/finallyaroundyieldin@contextmanagerfunctions. An exception in thewithbody is thrown into the generator at theyield; withoutfinally, the cleanup code is skipped. - Swallowing exceptions. A
@contextmanagerfunction that catches the exception (atry/exceptaroundyieldthat does not re-raise) suppresses it. Otherwise it propagates after cleanup. suppress()is narrow on purpose. It continues after the wholewithblock, not after the failing line. Do not wrap large blocks.ExitStackunwinds in reverse order and keeps going if one exit raises, which is exactly what you want for "open every file in this list" or conditional setup.redirect_stdoutonly affects Python-level printing throughsys.stdout, not output written by C code or subprocesses. It is not thread-safe because it changes a global.nullcontextavoids duplicate code paths:with (lock if needed else nullcontext()):.- Classes still work. For a context manager with a lot of state, or one that must be reused, a class with
__enter__and__exit__is clearer. Objects made by@contextmanagerare single-use. - Real files do not need
closing():open()already supportswith.
Related
with,try/except,yield,open()threading,asyncio- Lessons: Context managers, Generators