On this page
contextlib.ExitStack
Prev: contextlib.contextmanager | Up: contextlib | Next: contextlib.nullcontext
Rel: contextlib.AbstractAsyncContextManager, contextlib.AbstractContextManager, contextlib.aclosing, contextlib.asynccontextmanager
Ref: docs.python.org — contextlib.ExitStack
Tags: #public #python3 #stdlib #contextlib
Import
import contextlib
from contextlib import ExitStack
Signature & Overview
contextlib.ExitStack()
Context manager for dynamic management of a stack of exit callbacks.
Methods & Attributes
ExitStack.callback(self, callback, /, *args, **kwds)— Registers an arbitrary callback and arguments.ExitStack.close(self)— Immediately unwind the context stack.ExitStack.enter_context(self, cm)— Enters the supplied context manager.ExitStack.pop_all(self)— Preserve the context stack by transferring it to a new instance.ExitStack.push(self, exit)— Registers a callback with the standard exit method signature.
Usage
from contextlib import ExitStack
from pathlib import Path
import tempfile
with tempfile.TemporaryDirectory() as tmp:
paths = [Path(tmp) / f"f{i}.txt" for i in range(3)]
with ExitStack() as stack:
files = [stack.enter_context(p.open("w", encoding="utf-8")) for p in paths]
for i, fh in enumerate(files):
fh.write(str(i))
assert [p.read_text(encoding="utf-8") for p in paths] == ["0", "1", "2"]
Gotchas
- Dynamic number of context managers: Solves the "I need to open $N$ files at once" problem cleanly without nested
withblocks. stack.pop_all()transfers ownership: Lets a factory function set up resources safely, then hand cleanup responsibility to the caller if setup succeeds.
REPL Inspect
from contextlib import ExitStack
help(ExitStack)
Linked from
Related notes
- tuts/python3/stdlib_module/contextlib/contextmanager Linked here; links to this page; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/nullcontext Linked here; links to this page; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/contextlib/AbstractAsyncContextManager Linked here; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/AbstractContextManager Linked here; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/aclosing Linked here; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/asynccontextmanager Linked here; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/AsyncExitStack shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/chdir shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/closing shared tags: #contextlib, #stdlib