ExitStack Unwinds Dynamic Cleanup
Clean up dynamic resource sets with contextlib.ExitStack: enter_context registers handles, callback registers plain functions, and unwinding runs LIFO.
Code
import os
from contextlib import ExitStack
from tempfile import mkstemp
# mkstemp 只借它的原子命名;句柄立即关闭,后续按路径打开
paths = []
for _ in range(3):
fd, path = mkstemp(suffix=".txt")
os.close(fd)
paths.append(path)
# ExitStack:运行时才知道要打开多少资源时,统一登记、逆序释放
with ExitStack() as stack:
# 动态数量:循环里逐个登记,任何一步抛错全部自动关闭
handles = [stack.enter_context(open(path, "w", encoding="utf-8")) for path in paths]
handles[0].write("alpha")
handles[2].write("gamma")
print("open during:", sum(not h.closed for h in handles))
print("all closed :", [h.closed for h in handles])
print("contents :", [open(path, encoding="utf-8").read() for path in paths])
# callback:非上下文管理器的清理动作也登记进同一个栈,LIFO 释放
order = []
with ExitStack() as stack:
stack.callback(order.append, "first-registered")
stack.callback(order.append, "second-registered")
print("cleanup :", order)
for path in paths:
os.unlink(path)Output
Captured from a sandboxed run of this snippet in the build pipeline.
open during: 3
all closed : [True, True, True]
contents : ['alpha', '', 'gamma']
cleanup : ['second-registered', 'first-registered']What the code does
Repetition is confined to for _ in range(3) — the rest of the file is straight-line. Reach for tempfile and what you get is ExitStack, mkstemp — that is the whole API contact area.
Module-level bindings hold the data — paths, order — with no function scope in between.
Caveats
- External dependency:
tempfile— install it before running the snippet.
Applying it
Look for the open during:, all closed :, contents : prefixes when the file runs; they tie each line to its step.
Statements that matter
with ExitStack() as stack:
# 动态数量:循环里逐个登记,任何一步抛错全部自动关闭
handles = [stack.enter_context(open(path, "w", encoding="utf-8")) for path in paths]
handles[0].write("alpha")
handles[2].write("gamma")
print("open during:", sum(not h.closed for h in handles))
with ExitStack() as stack:
stack.callback(order.append, "first-registered")
stack.callback(order.append, "second-registered")
Interactive Tools for This Topic
FAQ
- Will the snippet run without installing packages?
- Yes, it runs as-is — nothing outside the built-in APIs is referenced. Every import resolves inside the standard library — `os`, `contextlib`, `tempfile`. Its state lives in module-level bindings: `paths`, `order`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.