Skip to content
Tutorials Center
My learning

Topics

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.

Python
from contextlib import contextmanager

@contextmanager
def tag(name):
    print(f"<{name}>")
    try:
        yield
    finally:
        print(f"</{name}>")

Try it

Python contextmanager, suppress and redirect_stdout

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 ExitStack, closing, nullcontext and ContextDecorator

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/finally around yield in @contextmanager functions. An exception in the with body is thrown into the generator at the yield; without finally, the cleanup code is skipped.
  • Swallowing exceptions. A @contextmanager function that catches the exception (a try/except around yield that does not re-raise) suppresses it. Otherwise it propagates after cleanup.
  • suppress() is narrow on purpose. It continues after the whole with block, not after the failing line. Do not wrap large blocks.
  • ExitStack unwinds 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_stdout only affects Python-level printing through sys.stdout, not output written by C code or subprocesses. It is not thread-safe because it changes a global.
  • nullcontext avoids 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 @contextmanager are single-use.
  • Real files do not need closing(): open() already supports with.