Beyond `with open()`: Writing Custom Context Managers
This article explains the context management protocol behind the with statement, shows how to write context managers as classes and as generators, and describes the standard tools and pitfalls of contextlib.
The present article addresses context managers, the objects that give meaning to the with statement and that guarantee the release of a resource regardless of how the code that uses it ends. The expression with open(path) as f: is familiar to almost every Python programmer, and the file it opens is closed even when an exception interrupts the block. The mechanism behind that guarantee, however, is not reserved for files: any class or generator function can provide it, which is the secret weapon that the following sections examine.
Cleanup Before with: try and finally
Releasing a resource reliably requires that the release run on every path out of the code, including the path of an exception. Before the with statement was introduced by PEP 343 in Python 2.5, the only tool for this purpose was the finally clause, as the following example shows with a simulated connection.
class Connection:
def __init__(self, name):
self.name = name
print(f"open {name}")
def close(self):
print(f"close {self.name}")
def run_query(connection):
raise ValueError("query failed")
connection = Connection("orders")
try:
try:
run_query(connection)
finally:
connection.close()
except ValueError as error:
print(f"error: {error}")
# Output: open orders
# Output: close orders
# Output: error: query failed
The connection is closed before the error reaches the outer handler, which is the correct behaviour. The cost lies in the structure: the acquisition and the release are separated from each other, the pattern must be repeated wherever the resource is used, and a single forgotten finally is enough to leak it.
The Context Management Protocol
The present section describes the protocol that the with statement relies on. An object is a context manager when its class defines two special methods, __enter__ and __exit__, which are looked up on the type of the object in the same way as the other methods examined in the article devoted to the data model. The statement with manager as target: executes four steps, which are the following:
- Entry. The method
__enter__is called, and its return value is bound totargetwhen the clauseasis present. - Block. The body of the
withstatement runs. - Exit. The method
__exit__is called with three arguments: the type, the value and the traceback of the exception that ended the block, orNonethree times when the block ended normally. - Decision. When
__exit__returns a true value, the exception is suppressed; otherwise, it propagates after the cleanup.
Online games with private dungeons work in a similar way: when a group enters, the game prepares a separate copy of the dungeon for it, and when the group leaves, the copy is discarded, whether the group defeated the final enemy, fell in combat or simply walked out. This means that __enter__ plays the part of the preparation and __exit__ the part of the dismantling, which runs on every way out of the block. The analogy, however, stops at this point for two reasons. First, the game reacts to a defeat on its own, whereas __exit__ receives the exception and decides whether it propagates. Second, the dismantling is guaranteed only for a group that actually entered: if __enter__ raises an exception, __exit__ is never called.
Writing a Context Manager Class
A class becomes a context manager as soon as it implements both methods, and the exception arguments of __exit__ allow it to behave differently on success and on failure. The following transaction commits when the block succeeds and rolls back when it fails, letting the exception continue.
class Transaction:
def __init__(self, log):
self.log = log
def __enter__(self):
self.log.append("begin")
return self
def __exit__(self, exc_type, exc_value, traceback):
if exc_type is None:
self.log.append("commit")
else:
self.log.append(f"rollback ({exc_type.__name__})")
return False # Never suppress the exception.
log = []
with Transaction(log):
log.append("write A")
try:
with Transaction(log):
log.append("write B")
raise KeyError("B")
except KeyError:
log.append("error propagated")
print(log)
# Output: ['begin', 'write A', 'commit', 'begin', 'write B',
# 'rollback (KeyError)', 'error propagated']
The log corroborates both paths: the first block ends with a commit, and the second ends with a rollback followed by the propagation of the original exception. The value returned by __enter__ is equally useful when the manager must report a result after the block, as in the following timer.
import time
class Timer:
def __enter__(self):
self.start = time.perf_counter()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.elapsed = time.perf_counter() - self.start
return False
with Timer() as timer:
total = sum(range(1_000_000))
print(total) # Output: 499999500000
print(f"{timer.elapsed:.3f} s") # Output: about 0.009 s (varies by machine)
The timer uses time.perf_counter() rather than time.time(), because it is the clock that the documentation recommends for measuring short intervals. For systematic measurements, the tools presented in the article devoted to profiling remain more appropriate than an ad hoc timer.
Generator-Based Context Managers with contextlib
The module contextlib offers a shorter route through the decorator @contextmanager, which turns a generator function into a context manager. The code before yield acts as __enter__, the yielded value is bound by as, and the code after yield acts as __exit__; an exception raised in the block reappears inside the generator at the point of the yield.
from contextlib import contextmanager
@contextmanager
def transaction(log):
log.append("begin")
try:
yield log
except Exception as error:
log.append(f"rollback ({type(error).__name__})")
raise
else:
log.append("commit")
log = []
with transaction(log) as entries:
entries.append("write A")
try:
with transaction(log):
raise KeyError("B")
except KeyError:
log.append("error propagated")
print(log)
# Output: ['begin', 'write A', 'commit', 'begin', 'rollback (KeyError)',
# 'error propagated']
The behaviour is identical to that of the class Transaction, in roughly half the lines. The try statement around yield is not optional, as the following example demonstrates with a manager that omits it.
from contextlib import contextmanager
@contextmanager
def fragile():
print("acquire")
yield
print("release")
try:
with fragile():
raise RuntimeError("boom")
except RuntimeError:
print("the release line never ran")
# Output: acquire
# Output: the release line never ran
Since the exception is raised at the yield, every line after it is skipped. Consequently, a generator-based manager must place its cleanup in a finally clause, or in an except clause that re-raises, exactly as the class-based version does implicitly through __exit__.
Ready-Made Tools in contextlib
The present section presents three tools of the standard library that solve frequent needs without writing a manager. The function suppress ignores the exceptions it receives, ExitStack manages a number of resources that is only known at runtime, and nullcontext provides a manager that does nothing, which is useful when a resource is optional.
from contextlib import ExitStack, nullcontext, suppress
with suppress(KeyError):
{}["missing"]
print("KeyError suppressed") # Output: KeyError suppressed
with ExitStack() as stack:
for name in ("a", "b", "c"):
print(f"open {name}")
stack.callback(print, f"close {name}")
print("work")
# Output: open a, open b, open c, work, close c, close b, close a (one per line)
with nullcontext("no lock needed") as value:
print(value) # Output: no lock needed
The output of ExitStack shows that the resources are released in reverse order of acquisition, which matches the behaviour of nested with statements. Furthermore, a manager created with @contextmanager can also be applied as a decorator to a function, so that each call of the function runs inside the context, a capability available since Python 3.2. Many objects of the standard library are context managers already, such as threading.Lock, tempfile.TemporaryDirectory and concurrent.futures.ThreadPoolExecutor, so writing a new manager is justified only when no existing one fits.
Pitfalls of Context Managers
Context managers fail in ways that short examples rarely reveal, and four pitfalls are particularly common, which are the following:
- Accidental suppression. Any true value returned by
__exit__suppresses the exception, so a method that returns a log message or a non-empty object silently discards errors. ReturningFalseorNoneexplicitly avoids this risk. - Failed entry. When
__enter__raises an exception,__exit__is not called, so any partial acquisition performed inside__enter__must be undone there. - Single use. The object returned by a function decorated with
@contextmanagerwraps one generator and cannot be used in a secondwithstatement; the function must be called again. - A forgotten return value. When
__enter__does not return anything, the target ofasisNone, which produces confusing errors only when that target is used.
The first pitfall is reproduced in the following example.
class Logger:
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
return "logged" # A true value: the exception disappears.
with Logger():
raise ValueError("lost")
print("execution continues as if nothing had happened")
# Output: execution continues as if nothing had happened
The ValueError never reaches the caller, because the string "logged" is a true value. This behaviour is legitimate when it is intended, as in suppress, but it should always be the result of an explicit return True and never a side effect.
When to Write a Context Manager
Consequently, the choice of tool depends on the shape of the resource and on the amount of state that the manager must keep. The criteria are summarized in the following table.
| Situation | Recommended tool |
|---|---|
A try/finally pair repeated in several places |
A custom context manager |
| Simple setup and cleanup around one block | A generator with @contextmanager and try/finally |
| State that must be inspected after the block, or reuse of the same object | A class with __enter__ and __exit__ |
| Ignoring one specific exception | contextlib.suppress |
| A variable number of resources | contextlib.ExitStack |
| A resource that is sometimes absent | contextlib.nullcontext |
| Asynchronous resources, such as network sessions | __aenter__ and __aexit__, or contextlib.asynccontextmanager |
Conclusion
It is concluded that a context manager joins the acquisition and the release of a resource in a single object, and that the with statement guarantees the release on every way out of the block once the entry has succeeded. Its magic rests on two special methods, or on one generator decorated with @contextmanager, and its main risks come from the value returned by __exit__ and from the cleanup that a generator places after yield without protection. Asynchronous context managers, which apply the same protocol to code based on async and await, are the natural extension of this topic and are developed in a future article of this series.