contextlib — context manager utilities

contextmanager, suppress, closing, ExitStack, and nullcontext, including exception suppression and stack unwinding, checked on Python 3.13.12.

contextlib provides helpers for with-statements. @contextmanager turns a generator into a context manager. suppress swallows selected exception types. ExitStack lets you enter a dynamic number of context managers and register callbacks. Examples were checked on Python 3.13.12.

suppressed exceptions are only the types you pass in. ExitStack still runs entered context managers and callbacks if the with-block raises, in last-in, first-out order.

Examples were checked against Python 3.13. See the official documentation for the complete API.

Python reference overview →

contextmanager, suppress, and closing

A generator decorated with @contextmanager yields once. The example prints enter, then the yielded value, then exit in a finally block so exit still runs if the body raises.

suppress(FileNotFoundError) ignores that error and no other. The missing path is a name inside a TemporaryDirectory, not a user file. A ValueError still propagates. closing(thing) calls thing.close() when the block exits, which the example uses on a tiny resource object.

contextmanager, suppress, closing

contextlib.contextmanager(func)
contextlib.suppress(*exceptions)
contextlib.closing(thing)

Build a context manager from a generator, ignore selected exceptions, or close a resource on exit.

ParameterDescription
*exceptionsThe exception types suppress should ignore. Other exceptions still propagate.
thingAn object with a close() method, for closing().

Returns: Each helper returns a context manager. contextmanager-wrapped functions yield the value you yield from the generator.

  • suppress is not a generic except Exception. Only the listed types are ignored.
python
import os
import tempfile
from contextlib import closing, contextmanager, suppress

@contextmanager
def mark(label):
    print("enter", label)
    try:
        yield label
    finally:
        print("exit", label)

with mark("a") as value:
    print("inside", value)

with tempfile.TemporaryDirectory(prefix="ctx-ref-") as folder:
    with suppress(FileNotFoundError):
        os.remove(os.path.join(folder, "missing.txt"))
    print("after-suppress")

try:
    with suppress(FileNotFoundError):
        raise ValueError("nope")
except ValueError as exc:
    print("not-suppressed", type(exc).__name__)

class Resource:
    def __init__(self):
        self.closed = False

    def close(self):
        self.closed = True

with closing(Resource()) as resource:
    print("open", resource.closed)
print("closed", resource.closed)

Expected output

enter a
inside a
exit a
after-suppress
not-suppressed ValueError
open False
closed True

Official documentation →

ExitStack, callbacks, and nullcontext

ExitStack.enter_context(cm) enters a context manager and schedules its exit. callback(print, "callback") registers an arbitrary function. When the example raises RuntimeError, the callback runs first, then exit 2, then exit 1, and the exception still propagates.

nullcontext(enter_result) yields that value and does nothing else. pop_all() moves the current stack to a new ExitStack so the original with-block can exit without closing those resources; the example then calls leftover.close() to run them.

ExitStack, enter_context, callback, pop_all, nullcontext

contextlib.ExitStack()
ExitStack.enter_context(cm)
ExitStack.callback(callback, /, *args, **kwds)
ExitStack.pop_all()
contextlib.nullcontext(enter_result=None)

Enter a dynamic stack of context managers, register callbacks, transfer the stack, or use a no-op context.

ParameterDescription
cmA context manager passed to enter_context.
callback, *args, **kwdsA function and its arguments, run on exit in last-in, first-out order with the other callbacks and exits.
enter_resultThe value nullcontext yields.

Returns: enter_context returns the entered context's __enter__ result. pop_all returns a new ExitStack that owns the transferred callbacks.

  • The RuntimeError in the example exists only to show that cleanup still runs. It is caught in the same script.
python
from contextlib import ExitStack, contextmanager, nullcontext

@contextmanager
def mark(label):
    print("enter", label)
    try:
        yield label
    finally:
        print("exit", label)

try:
    with ExitStack() as stack:
        first = stack.enter_context(mark("1"))
        second = stack.enter_context(mark("2"))
        stack.callback(print, "callback")
        print("yielded", first, second)
        raise RuntimeError("fail")
except RuntimeError:
    print("caught")

with nullcontext("held") as value:
    print("null", value)

with ExitStack() as stack:
    stack.enter_context(mark("keep"))
    leftover = stack.pop_all()
print("after-parent")
leftover.close()
print("after-close")

Expected output

enter 1
enter 2
yielded 1 2
callback
exit 2
exit 1
caught
null held
enter keep
after-parent
exit keep
after-close

Official documentation →