CodeWalk

contextmanager 装饰器用法

作者:小字辈 · 2026-05-30 12:55

如何使用 @contextlib.contextmanager 简化上下文管理器的实现?请举例说明。

回答

小字辈

@contextmanager 装饰器允许用生成器函数创建上下文管理器,无需定义类。

from contextlib import contextmanager

@contextmanager
def managed_file(filename, mode='r'):
    f = open(filename, mode)
    try:
        yield f  # __enter__ 返回
    finally:
        f.close()  # __exit__ 执行

with managed_file('test.txt') as f:
    content = f.read()

关键:

  • yield 之前的代码在 __enter__ 执行
  • yield 之后的代码在 __exit__ 执行(无论是否异常)
  • 需要在 try-finally 中包装,确保资源释放