Skip to main content

contextlib

Helpers for building, composing, and customising context managers. The decorator @contextmanager adapts a generator into a sync manager; @asynccontextmanager does the same for async generators.

Source-of-record: Lib/contextlib.py, contextlib docs.

Decorators

DecoratorAdapts
@contextmanagerA generator yielding once.
@asynccontextmanagerAn async generator yielding once.

The generator yields the resource. Exceptions thrown into the generator on exit propagate through, unless the generator catches them and exits normally.

Helpers

HelperRole
closing(thing)Calls thing.close() on exit.
aclosing(thing)Awaits thing.aclose() on exit.
suppress(*exceptions)Swallow the listed exceptions.
redirect_stdout(target)Patch sys.stdout for the block.
redirect_stderr(target)Patch sys.stderr for the block.
nullcontext(enter_result=None)No-op manager; useful as a placeholder.
chdir(path)Change cwd for the block.

Stacks

ClassVariantUse
ExitStacksyncDynamic composition; LIFO unwinding.
AsyncExitStackasyncMix of sync and async managers.

ExitStack methods:

MethodBehaviour
enter_context(cm)Enter cm and record it.
push(cm_or_exit)Record an existing exit callback.
callback(fn, *args, **kw)Record a plain function to call.
pop_all()Transfer callbacks to a fresh stack.
close()Run all callbacks.

AsyncExitStack adds enter_async_context, push_async_exit, push_async_callback, aclose.

Base classes

ClassImplements
ContextDecoratorMix-in: lets a manager double as a decorator.
AsyncContextDecoratorSame, for async.
AbstractContextManagerABC with __enter__ and __exit__.
AbstractAsyncContextManagerABC with __aenter__ and __aexit__.

Suppress patterns

with suppress(FileNotFoundError):
os.remove(path)

suppress catches subclass exceptions matching any of the listed types and continues. Behaves like try/except: pass.

Gopy status

AreaState
@contextmanager, @asynccontextmanagerComplete.
closing, aclosing, suppress, redirects, nullcontext, chdirComplete.
ExitStack, AsyncExitStackComplete.
ABCsComplete.

Reference

  • CPython 3.14: contextlib.
  • Lib/contextlib.py.
  • module/contextlib/. gopy port.