上下文管理器
中等 约 35 分钟
你将构建什么
一个基于类的 Timer 上下文管理器和一个基于装饰器的文件处理上下文管理器,处理设置、拆卸和异常。
学习目标
- 实现 __enter__ 和 __exit__ 方法
- 用 contextlib.contextmanager 实现基于装饰器的管理器
- 在 __exit__ 中处理异常
- 理解 with 语句的保证
前置要求
- 类与 __init__
- try/finally 清理
- with 语句
步骤
- 1
编写基于类的 Timer
上下文管理器类实现 __enter__(设置,返回资源)和 __exit__(拆卸,处理异常)。编写测量 with 块内时间的 Timer。
代码import time class Timer: def __enter__(self): self.start = time.perf_counter() return self def __exit__(self, exc_type, exc_val, exc_tb): self.elapsed = time.perf_counter() - self.start print(f"Elapsed: {self.elapsed:.4f}s") return False # don't suppress exceptions with Timer() as t: sum(range(1_000_000)) # prints 'Elapsed: 0.0x s'预期结果
with 块结束后打印经过时间。
- 2
在 __exit__ 中处理异常
若 with 块内发生异常,__exit__ 接收异常信息。返回 True 抑制,False 传播。测试两种行为。
提示
从 __exit__ 返回 True 会吞掉异常——慎用,如对预期错误。
- 3
使用 contextlib.contextmanager
@contextmanager 装饰器将生成器函数转为上下文管理器。yield 标记 with 块运行点。yield 前是设置,后是拆卸。
代码from contextlib import contextmanager @contextmanager def open_db(url): print(f"Connecting to {url}") conn = {"url": url, "open": True} # mock connection try: yield conn finally: conn["open"] = False print(f"Closing {url}") with open_db("localhost:5432") as db: print(f"Using {db['url']}, open={db['open']}") # prints: Connecting, Using, Closing预期结果
设置在块前运行,拆卸在块后运行(即使异常)。
- 4
嵌套上下文管理器
可嵌套 with 语句管理多个资源。Python 3.10+ 允许括号实现多行嵌套。测试嵌套计时器和连接。
提示
contextlib 的 ExitStack 可管理动态数量的上下文管理器。
- 5
构建临时目录管理器
编写一个创建临时目录、yield 其路径并在退出时删除(含所有内容)的上下文管理器。用 tempfile 和 shutil 实现。
代码import tempfile, shutil, os from contextlib import contextmanager @contextmanager def temp_dir(): path = tempfile.mkdtemp() try: yield path finally: shutil.rmtree(path) with temp_dir() as d: print(f"Working in {d}") with open(os.path.join(d, "file.txt"), "w") as f: f.write("hello") # directory and file are now gone预期结果
临时目录在块内存在,块后删除。
自己动手试试
起始代码
class Timer:
def __enter__(self): pass
def __exit__(self, *args): pass解决方案代码
class Timer:
def __enter__(self): self.s = time.perf_counter(); return self
def __exit__(self, *a): print(f"{time.perf_counter()-self.s:.4f}s")你学到了什么
你构建了上下文管理器——Python 的 RAII 资源管理机制。它们即使异常也保证清理,用于文件、锁、数据库连接等。
相关资源
相关课程
- 类
基于类的上下文管理器使用 dunder 方法。
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。