找出报告上下文管理器里的 bug

来自 上下文管理器
Python 3.14 进阶 5分钟 找出 1处问题

找出代码块失败后报表文件仍保持打开的原因。

Python
from contextlib import contextmanager

@contextmanager
def open_report(path):
    handle = open(path, "w", encoding="utf-8")
    yield handle
    handle.close()

try:
    with open_report("report.txt") as report:
        report.write("draft")
        raise ValueError("invalid report")
except ValueError:
    print(report.closed)
在试验场中打开
报告错误