← 中文资源

简体中文版本

ExitStack 逆序释放动态资源

ExitStack 管理运行时才确定数量的资源:enter_context 逐个登记句柄,callback 登记普通清理动作,离开时逆序释放,任何一步抛错都不泄漏。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

open during: 3
all closed : [True, True, True]
contents   : ['alpha', '', 'gamma']
cleanup    : ['second-registered', 'first-registered']

实现说明

重复被限制在 for _ in range(3) 里——其余代码按顺序各跑一遍。 顶层就这几处状态:paths、order。

使用要点

  • 演示输出是带标签的(open during:、all closed :),每个操作都会留下自己的一行标注。

常见问题

不安装任何包也能运行吗?

可以,开箱即跑——没有引用任何内建 API 之外的东西。 全部导入都来自标准库:os、contextlib、tempfile。 文件的状态由几个模块级绑定持有:paths、order。

核心语句

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")

代码示例

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)