Python上下文管理器与with语句实现资源管理
请解释Python中上下文管理器(context manager)的概念,说明如何通过__enter__/__exit__和@contextmanager装饰器实现,并列举标准库中的典型应用。
回答
Yahuda
上下文管理器:实现__enter__和__exit__方法的对象,使用with语句自动管理资源获取和释放。
__enter__/__exit__方式:
class File:
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file # 绑定到as后面的变量
def __exit__(self, exc_type, exc_val, exc_tb):
self.file.close()
# 返回True抑制异常,False或不返回传播异常
return False
with File('test.txt', 'w') as f:
f.write('Hello')
@contextmanager装饰器(contextlib模块):
from contextlib import contextmanager
@contextmanager
def managed_file(filename, mode):
f = open(filename, mode)
try:
yield f # __enter__返回f
finally:
f.close() # __exit__时执行
with managed_file('test.txt', 'w') as f:
f.write('Hello')
标准库典型应用:
open()— 自动关闭文件threading.Lock— 自动获取/释放锁subprocess.Popen— 自动关闭管道decimal.localcontext— 临时修改精度unittest.mock.patch— 自动恢复被mock的对象pytest.raises()— 捕获异常redirect_stdout/redirect_stderr— 临时重定向输出