Cleaning Up an Unknown Number of Resources with Python's ExitStack
This article explains how contextlib.ExitStack manages a number of context managers known only at run time, undoes partial failures, transfers ownership with pop_all and handles exceptions raised during cleanup.
The with statement guarantees that a resource is released, but it assumes that the number of resources is known when the code is written: two files require two managers, and three files require three, each one indented further to the right. The present article addresses contextlib.ExitStack, a context manager that collects any number of other managers and cleanup functions at run time and releases them all, in reverse order, when its own block ends. It examines how resources are registered, how a partial failure is undone, how ownership of the resources can be transferred out of the block, and which errors appear when cleanup itself fails. Managing a number of resources that is only known at run time with a single, flat with statement is the secret weapon of ExitStack.
A Variable Number of Resources
The method enter_context enters a context manager, registers its exit method on the stack and returns whatever the manager's __enter__ returns, so it replaces a with statement that cannot be written in advance. When the block ends, normally or through an exception, the stack calls the registered exit methods from the last to the first, exactly as nested with statements would. The following example opens a list of resources, the third of which fails, using a small generator-based manager instead of real files so that it runs without touching the disk.
from contextlib import ExitStack, contextmanager
@contextmanager
def resource(name, fail=False):
if fail:
raise OSError(f"cannot open {name}")
print(f"open {name}")
try:
yield name
finally:
print(f"close {name}")
try:
with ExitStack() as stack:
for name, fail in [("a", False), ("b", False), ("c", True)]:
stack.enter_context(resource(name, fail))
except OSError as error:
print(error)
# Output: open a
# Output: open b
# Output: close b
# Output: close a
# Output: cannot open c
The two resources that were opened are closed in reverse order before the exception reaches the caller, so a failure in the middle of the loop leaves nothing open. The same code serves for files, sockets, locks or several mock.patch managers whose targets come from a list, a use that complements the techniques described in the article devoted to monkey patching. For asynchronous managers, AsyncExitStack, available since Python 3.7, offers the same operations with enter_async_context and aclose.
Callbacks, Exit Functions and Transfer of Ownership
Strategy games refund the resources of a building whose construction is cancelled before it is completed, so that a failed order leaves the player exactly as before. This means that an operation which acquires several resources should either keep all of them or release all of them, and ExitStack provides the three methods that implement that rule. The method callback registers any function with its arguments, push registers an exit function that receives the exception details, and pop_all moves every registered cleanup to a new stack without running it. The analogy, however, stops at this point, because the release is not a single transaction: each cleanup runs separately, in reverse order, and one that fails can leave the release incomplete.
from contextlib import ExitStack, contextmanager
@contextmanager
def resource(name):
print(f"open {name}")
try:
yield name
finally:
print(f"close {name}")
def open_all(names):
with ExitStack() as stack:
handles = [stack.enter_context(resource(n)) for n in names]
stack.callback(print, "registered cleanup")
return handles, stack.pop_all()
handles, owner = open_all(["x", "y"])
print("in use:", handles)
owner.close()
# Output: open x
# Output: open y
# Output: in use: ['x', 'y']
# Output: registered cleanup
# Output: close y
# Output: close x
Without pop_all, the resources would be closed when open_all returns; with it, the function either completes and hands every resource to the caller, or fails and releases what it had opened, the same guarantee that the documentation uses to clean up inside an __enter__ method. The returned stack is an ordinary ExitStack, so the caller can close it explicitly or use it in its own with statement. A facade that coordinates several subsystems benefits from the same pattern when a partial failure must be undone, as discussed in the article devoted to the Facade pattern.
Pitfalls of ExitStack
The stack reproduces the semantics of nested with statements, including their handling of exceptions, so most errors come from forgetting that its cleanups run later, in reverse, and with the exception state of the block. Six pitfalls are distinguished, which are the following:
- Using the stack without
with. AnExitStackthat is created but never entered or closed releases nothing. - Accidental suppression. An exit function registered with
pushthat returns a true value suppresses the exception of the block, whereas functions registered withcallbacknever receive the exception and cannot suppress it. - Exceptions during cleanup. An exception raised by a cleanup replaces the exception of the block, which then survives only as the
__context__of the new one. - Objects that are not context managers. Since Python 3.11,
enter_contextraisesTypeErrorfor them; earlier versions raisedAttributeError. - Forgotten ownership. The stack returned by
pop_allmust be closed by someone, or its resources remain open. - A stack where a plain
withsuffices. A fixed number of managers is clearer as a singlewithstatement with parenthesized managers, a syntax officially supported since Python 3.10.
The second, third and fourth pitfalls are reproduced in the following example.
from contextlib import ExitStack
with ExitStack() as stack:
stack.push(lambda *exc_info: True)
raise RuntimeError("lost")
print("the exception was suppressed") # Output: the exception was suppressed
def failing_cleanup():
raise ValueError("cleanup failed")
try:
with ExitStack() as stack:
stack.callback(failing_cleanup)
raise KeyError("body")
except Exception as error:
print(repr(error), repr(error.__context__))
# Output: ValueError('cleanup failed') KeyError('body')
try:
ExitStack().enter_context(42)
except TypeError as error:
print(type(error).__name__) # Output: TypeError
The lambda returns True, so the RuntimeError disappears silently, a behaviour that is correct for a manager such as contextlib.suppress but surprising in an exit function written by accident. The failing cleanup turns a KeyError from the body into a ValueError, so code that catches KeyError would miss the original problem; cleanup functions should therefore be as simple as possible and should not raise.
Choosing How to Manage Several Resources
Consequently, ExitStack is the right tool when the number of resources, or the decision to keep them, is only known at run time, as the following table summarizes.
| Situation | Recommended approach |
|---|---|
| One resource | A plain with statement |
| A fixed, small number of resources | One with statement with parenthesized managers |
| A number of resources known only at run time | ExitStack.enter_context in a loop |
| Cleanup that is a function, not a manager | ExitStack.callback |
| Resources that must outlive the function that acquires them | ExitStack.pop_all |
| Asynchronous resources | AsyncExitStack |
| A single reusable acquire-and-release step | A custom context manager |
Conclusion
It is concluded that ExitStack turns any number of context managers and cleanup functions into a single with statement, that it releases them in reverse order even when acquisition fails half-way, and that pop_all lets a function hand its resources to the caller only after every one of them was acquired. This magic keeps the semantics of nested with statements, so exit functions can suppress exceptions and failing cleanups can replace them, as the managers described in the article devoted to custom context managers do individually. Searching several dictionaries as if they were one, with a defined order of priority, is the purpose of collections.ChainMap, which is developed in a future article of this series.