Context manager pattern
The context manager pattern is acquire/release as an object you use with with. Setup runs on entry, teardown on exit, including when the block raises.
Detailed Explanation
Locks, files, transactions, and monkeypatches all have the same shape: you must pair a start with an end. The context manager pattern is that pair as a first-class object. __enter__ / __exit__, or a generator decorated with @contextmanager, or an async pair for async with.
As a design pattern it is how you expose resources in an API. engine.begin() returning a transaction context is better than engine.start() plus a documented engine.rollback() callers forget. Libraries that ignore this (a open_session() with a manual close) grow leaks.
The pattern composes. ExitStack opens n managers. Nesting with db, lock: acquires in order and releases in reverse. That reverse order is part of the design: the last acquired is the first released, like a stack.
Do not do real work in __enter__ beyond acquiring. Do not swallow exceptions in __exit__ unless the manager's job is suppression. Do not start threads you cannot join in __exit__.
Testing uses the same pattern: with patch(...), with pytest.raises(...). A fixture that yields is a context manager under the hood.
Related ideas: RAII in C++, try-with-resources in Java, using in C#. Python's version is explicit at the call site (with) and therefore greppable.
When a resource is process-wide and long-lived (a connection pool), the facade that owns the process lifetime (lifespan in FastAPI, atexit) is the outer context manager. Request-scoped resources are inner ones.
Code Examples
from contextlib import contextmanager
@contextmanager
def transaction(store: dict):
snapshot = dict(store)
try:
yield store
except Exception:
store.clear()
store.update(snapshot)
raise
db = {"cents": 100}
try:
with transaction(db):
db["cents"] -= 40
raise RuntimeError("boom")
except RuntimeError:
pass
print(db) # {'cents': 100}from contextlib import ExitStack, closing
from io import StringIO
with ExitStack() as stack:
a = stack.enter_context(closing(StringIO("one")))
b = stack.enter_context(closing(StringIO("two")))
print(a.read(), b.read()) # one twoCommon Gotchas
Work after `yield` without `finally`
an exception in the block skips release. Always `try` / `yield` / `finally`.
Returning `True` from `__exit__`
the exception disappears. Almost never what an API user wants.
A long-lived object used as a one-shot context manager
files cannot be re-opened by a second `with` on the same instance. Document whether re-entry is allowed.
`async with` is the async form
see context managers and asyncio. Do not mix.