上下文 Managers
Manage resources 使用使用语句: __enter__/__exit__, contextlib, and 异步上下文 managers.
你将学到
- Use 使用语句 for resource management
- Implement __enter__ and __exit__ protocol
- 创建上下文 managers 使用 contextlib.contextmanager
- Handle 异常 in __exit__
- Apply practical 上下文 manager 模式
概念讲解
The with Statement
The 使用 statement guarantees that setup and cleanup code always runs, even if an exception occurs. This is the standard way to manage resources (files, locks, connections):
with open("数据.txt") as f:
content = f.read()
# f.close() is called automatically here, even if an error occurred
Without 使用, you would need a try/finally to ensure cleanup:
f = open("数据.txt")
try:
content = f.read()
finally:
f.close()
The 使用 statement is cleaner and guarantees cleanup — you never forget to close the resource.
The Context Manager Protocol
A context manager implements two methods:
__enter__()— runs at the start; its return value is assigned to theasvariable__exit__(exc_type, exc_val, exc_tb)— runs at the end; receives exception info if one occurred
class FileManager:
def __init__(self, filename, mode="r"):
self.filename = filename
self.mode = mode
self.file = None
def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file # this is assigned to 'f' in 'with ... as f'
def __exit__(self, exc_type, exc_val, exc_tb):
if self.file:
self.file.close()
# Return False (or None) to propagate any exception
# Return True to suppress the exception
return False
with FileManager("数据.txt") as f:
content = f.read()
__exit__ receives three arguments describing any exception that occurred inside the 使用 block. If no exception occurred, all three are 无. Returning 真 from __exit__ suppresses the exception; returning 假 or 无 lets it propagate.
contextlib.contextmanager
Writing a class with __enter__/__exit__ is verbose. The @contextmanager decorator lets you write a context manager as a generator function:
from contextlib import contextmanager
@contextmanager
def open_file(filename, mode="r"):
f = open(filename, mode)
try:
yield f # this is the 'as' value
finally:
f.close() # cleanup always runs
with open_file("数据.txt") as f:
content = f.read()
Everything before yield is the setup (__enter__). The yield value is assigned to the as variable. Everything after yield is the cleanup (__exit__). Use try/finally around the yield to ensure cleanup runs even on exception.
Practical: Timing Context Manager
import time
from contextlib import contextmanager
@contextmanager
def timer(label="操作"):
start = time.perf_counter()
try:
yield
finally:
elapsed = time.perf_counter() - start
print(f"{label} took {elapsed:.4f}s")
with timer("排序"):
sorted(range(1_000_000, 0, -1))
# Sorting took 0.1234s
Practical: Database Transaction
@contextmanager
def transaction(db):
db.begin()
try:
yield db
db.commit()
except Exception:
db.rollback()
raise
with transaction(db) as conn:
conn.execute("INSERT INTO 用户 ...")
conn.execute("INSERT INTO 顺序 ...")
# Commits if no error, rolls back if an exception occurred
This is how ORMs like Django and SQLAlchemy manage transactions — the 使用 block commits on success and rolls back on any exception.
contextlib.suppress
Suppress specific exceptions without a try/except:
from contextlib import suppress
# Instead of:
try:
os.remove("temp.txt")
except FileNotFoundError:
pass
# Use:
with suppress(FileNotFoundError):
os.remove("temp.txt")
contextlib.redirect_stdout
Redirect print() output (useful for testing):
from contextlib import redirect_stdout
import io
buffer = io.StringIO()
with redirect_stdout(buffer):
print("这个 goes 到 buffer, 不 console")
captured = buffer.getvalue()
Nested Context Managers
You can nest 使用 statements or use ExitStack for dynamic nesting:
# Nested with
with open("输入.txt") as infile, open("输出.txt", "w") as outfile:
for line in infile:
outfile.write(line.upper())
# ExitStack for a dynamic number of files
from contextlib import ExitStack
files = [".txt", "b.txt", "c.txt"]
with ExitStack() as stack:
handles = [stack.enter_context(open(f)) for f in files]
# all files are closed when the block exits
Exception Handling in __exit__
class SafeDivision:
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is ZeroDivisionError:
print("Caught division 通过零 — suppressing")
return True # suppress the exception
return False # let other exceptions propagate
with SafeDivision():
result = 10 / 0 # exception is suppressed
print("Continues 通常")
Returning 真 from __exit__ suppresses the exception — the 使用 block continues as if nothing happened. Use this sparingly, as it can hide bugs.
示例代码
import time
from contextlib import contextmanager, suppress
# Class-based context manager
class FileManager:
def __init__(self, filename, mode="w"):
self.filename = filename
self.mode = mode
self.file = None
def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
if self.file:
self.file.close()
return False
with FileManager("test.txt", "w") as f:
f.write("Hello, context managers!")
print("File written and closed automatically")
# contextlib.contextmanager — the easy way
@contextmanager
def timer(label="Operation"):
start = time.perf_counter()
try:
yield
finally:
elapsed = time.perf_counter() - start
print(f" {label} took {elapsed:.6f}s")
with timer("Sorting"):
sorted(range(100000, 0, -1))
# suppress — ignore specific exceptions
import os
with suppress(FileNotFoundError):
os.remove("nonexistent_file.txt") # no error raised
print("Suppressed FileNotFoundError successfully")
# Nested context managers
with open("test.txt", "w") as f1, open("test2.txt", "w") as f2:
f1.write("file 1 content")
f2.write("file 2 content")
print("Both files written and closed")
# Practical: indented output
@contextmanager
def indent(level=2):
print(" " * level + "Start of block")
try:
yield
finally:
print(" " * level + "End of block")
with indent():
print(" Inside the block")
# Exception suppression in __exit__
class SafeDivision:
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is ZeroDivisionError:
print(" Caught and suppressed ZeroDivisionError")
return True
return False
with SafeDivision():
result = 10 / 0
print("Continued after suppressed exception")
Shows 类-based FileManager, @contextmanager decorator for timer, suppress() for ignoring 异常, nested 使用语句, 自定义 indent 上下文 manager, and 异常 suppression in __exit__.
动手试一试
- JSON Formatter
File and 数据库上下文 managers 是 used 当读取/编写 JSON.
- CSV 到 JSON
File 上下文 managers manage CSV file handles 期间 conversion.
常见错误
错误写法
Forgetting try/最后围绕 yield in @contextmanager 函数
正确做法
如果异常 occurs 内部使用块 and yield 是不 in try/最后, cleanup code 之后 yield 从不运行. 总是 wrap yield in try/最后到 guarantee cleanup: try: yield 值最后: cleanup().
错误写法
Returning 真从 __exit__ unintentionally, 哪个 suppresses 所有异常
正确做法
__exit__ returning 真 suppresses 异常那个 occurred in 使用块. 这个 hides bugs. 仅返回真 当你 intentionally 想要到 suppress 特定异常. 返回假 or 无到 let 异常 propagate 通常.
相关资源
相关速查表
- Python Cheatsheet
上下文 manager protocol, contextlib, and 常见模式.
练习 上下文 Managers
2 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。