首页 › Python 进阶 › 上下文管理器

上下文管理器

with 语句保证资源在使用后被正确释放,即使中途发生异常也不例外。最常见的例子是文件:

with open("data.txt", "w", encoding="utf-8") as f:
    f.write("hello")
# 离开 with 块时文件自动关闭

自己实现上下文管理器

实现 __enter__ 和 __exit__ 两个方法即可:

import time

class Timer:
    def __enter__(self):
        self.start = time.perf_counter()
        return self

    def __exit__(self, exc_type, exc, tb):
        self.cost = time.perf_counter() - self.start
        print(f"耗时 {self.cost:.3f} 秒")
        return False      # 不吞掉异常

with Timer():
    sum(range(1_000_000))

contextlib

用生成器写起来更简单:

from contextlib import contextmanager
import os

@contextmanager
def working_dir(path):
    old = os.getcwd()
    os.chdir(path)
    try:
        yield
    finally:
        os.chdir(old)

with working_dir("/tmp"):
    print(os.getcwd())

yield 之前的代码相当于 __enter__,finally 中的代码相当于 __exit__。

练习题

学完本节后,试着独立完成下面的练习,再展开参考答案对照。

练习 1 用 contextlib.contextmanager 写一个 timer(label),在代码块结束时输出耗时。

查看参考答案
import time
from contextlib import contextmanager

@contextmanager
def timer(label):
    start = time.perf_counter()
    try:
        yield
    finally:
        print(f"{label} 完成")

with timer("求和"):
    total = sum(range(1_000_000))
print(total)
参考输出:
求和 完成
499999500000