Python上下文管理器实战:5个高级资源管理技巧
1. 基础上下文管理器
使用类实现文件操作上下文管理:
class FileHandler:
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
self.file.close()
if exc_type is not None:
print(f"操作异常: {exc_val}")
return True
# 使用
with FileHandler('data.txt', 'w') as f:
f.write('Hello, Context Manager!')
2. 使用contextlib简化
通过生成器创建上下文管理器:
from contextlib import contextmanager
@contextmanager
def timer_context(name):
start = time.time()
try:
yield
finally:
print(f"{name}耗时: {time.time() - start:.2f}秒")
# 使用
with timer_context("数据处理"):
data = [x**2 for x in range(1000000)]
3. 数据库事务管理
实现自动提交/回滚的事务:
class DBTransaction:
def __init__(self, connection):
self.conn = connection
def __enter__(self):
self.conn.begin()
return self.conn.cursor()
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is None:
self.conn.commit()
else:
self.conn.rollback()
return True
# 使用
with DBTransaction(db_conn) as cursor:
cursor.execute("INSERT INTO users VALUES (?, ?)", ("张三", 30))
4. 临时环境管理
创建临时工作目录:
import tempfile
import shutil
from contextlib import contextmanager
@contextmanager
def temp_directory():
temp_dir = tempfile.mkdtemp()
try:
yield temp_dir
finally:
shutil.rmtree(temp_dir)
# 使用
with temp_directory() as temp_dir:
print(f"临时目录: {temp_dir}")
# 在临时目录中工作
实现方式 | 类实现 | contextlib |
---|---|---|
代码量 | 较多 | 较少 |
灵活性 | 高 | 中 |
适用场景 | 复杂逻辑 | 简单场景 |
5. 多上下文嵌套
同时管理多个资源:
from contextlib import ExitStack
def process_files(source, dest):
with ExitStack() as stack:
src_file = stack.enter_context(open(source, 'r'))
dest_file = stack.enter_context(open(dest, 'w'))
log_file = stack.enter_context(open('process.log', 'a'))
content = src_file.read()
dest_file.write(content.upper())
log_file.write(f"处理完成: {source} -> {dest}n")
# 使用
process_files('input.txt', 'output.txt')
合理使用上下文管理器可以确保资源被正确释放,特别适合文件操作、数据库连接、锁管理等需要精确控制生命周期的场景。