On this page
contextlib
Prev: configparser | Up: stdlib_module | Next: contextvars
Rel: sys, sysconfig, builtins, warnings, dataclasses
Ref: docs.python.org — contextlib
Tags: #public #python3 #stdlib
Import
import contextlib
Overview
Utilities for writing and composing context managers (with / async with blocks) cleanly—turning setup/teardown generators into @contextmanagers, managing a dynamic number of resources with ExitStack, suppressing expected exceptions with suppress, and ensuring .close() runs with closing.
Quick Start
from contextlib import contextmanager
@contextmanager
def managed_tag(name: str):
out = [f"<{name}>"]
try:
yield out
finally:
out.append(f"</{name}>")
with managed_tag("section") as buf:
buf.append("body")
assert "".join(buf) == "<section>body</section>"
Implementation Walkthrough
1. Managing a Variable Number of Resources with ExitStack
When you don't know how many files or connections you'll open until runtime, ExitStack unwinds them in strict LIFO order even if one fails partway through:
from contextlib import ExitStack
from pathlib import Path
def read_all(paths: list[Path]) -> list[str]:
with ExitStack() as stack:
handles = [stack.enter_context(p.open("r", encoding="utf-8")) for p in paths]
return [fh.read() for fh in handles]
2. Clean Cleanup Helpers (suppress, closing, redirect_stdout)
from contextlib import redirect_stdout, suppress
import io
with suppress(KeyError):
del {"a": 1}["missing"]
captured = io.StringIO()
with redirect_stdout(captured):
print("captured line")
assert captured.getvalue() == "captured line\n"
Gotchas & Boundaries
- Always wrap
yieldintry ... finally:inside@contextmanager: Withoutfinally, an exception inside thewithblock skips your cleanup code. - Keep
suppress()narrow: Suppress only specific, expected exceptions (FileNotFoundError,KeyError), never broadException. redirect_stdout()mutates globalsys.stdout: It is not thread-safe; avoid it in multithreaded code and pass explicitfile=streams instead.- Use
AsyncExitStackand@asynccontextmanagerforasync withresources.
Common Functions
- contextlib.asynccontextmanager() —
asynccontextmanager(func)— @asynccontextmanager decorator. - contextlib.contextmanager() —
contextmanager(func)— @contextmanager decorator.
Classes & Objects
- contextlib.AbstractAsyncContextManager — An abstract base class for asynchronous context managers.
- contextlib.AbstractContextManager — An abstract base class for context managers.
- contextlib.aclosing — Async context manager for safely finalizing an asynchronously cleaned-up resource such as an async generator, calling its
aclose()method. - contextlib.AsyncExitStack — Async context manager for dynamic management of a stack of exit callbacks. (Methods:
.aclose(),.callback(),.enter_async_context(),.enter_context(),.pop_all(),.push()) - contextlib.chdir — Non thread-safe context manager to change the current working directory.
- contextlib.closing — Context to automatically close something at the end of a block.
- contextlib.ContextDecorator — A base class or mixin that enables context managers to work as decorators.
- contextlib.ExitStack — Context manager for dynamic management of a stack of exit callbacks. (Methods:
.callback(),.close(),.enter_context(),.pop_all(),.push()) - contextlib.nullcontext — Context manager that does no additional processing.
- contextlib.redirect_stderr — Context manager for temporarily redirecting stderr to another file.
- contextlib.redirect_stdout — Context manager for temporarily redirecting stdout to another file.
- contextlib.suppress — Context manager to suppress specified exceptions After the exception is suppressed, execution proceeds with the next statement following the with statement.
Linked from
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/atexit
- tuts/python3/stdlib_module/builtins
- tuts/python3/stdlib_module/configparser
- tuts/python3/stdlib_module/contextlib/AbstractAsyncContextManager
- tuts/python3/stdlib_module/contextlib/AbstractContextManager
- tuts/python3/stdlib_module/contextlib/aclosing
- tuts/python3/stdlib_module/contextlib/asynccontextmanager
- tuts/python3/stdlib_module/contextlib/AsyncExitStack
- tuts/python3/stdlib_module/contextlib/chdir
- tuts/python3/stdlib_module/contextlib/closing
- tuts/python3/stdlib_module/contextlib/ContextDecorator
- tuts/python3/stdlib_module/contextlib/contextmanager
- tuts/python3/stdlib_module/contextlib/ExitStack
- tuts/python3/stdlib_module/contextlib/nullcontext
- tuts/python3/stdlib_module/contextlib/redirect_stderr
- tuts/python3/stdlib_module/contextlib/redirect_stdout
- tuts/python3/stdlib_module/contextlib/suppress
- tuts/python3/stdlib_module/contextvars
- tuts/python3/stdlib_module/dataclasses
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/stdlib_module/sys
- tuts/python3/stdlib_module/sysconfig
- tuts/python3/stdlib_module/warnings
- tuts/python3/tutorials/intermediate_python_and_software_engineering/error_handling_and_context_managers
Related notes
- tuts/python3/stdlib_module/builtins Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/configparser Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/contextlib/AbstractAsyncContextManager Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/contextlib/AbstractContextManager Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/contextlib/aclosing Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/contextlib/asynccontextmanager Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/contextlib/AsyncExitStack Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/contextlib/chdir Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/contextlib/closing Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/contextlib/ContextDecorator Linked here; links to this page; shared tags: #stdlib