Python上下文管理:with语句执行原理
什么是上下文管理器
上下文管理器(Context Manager)是 Python 中用于管理资源分配和释放的一种机制。它允许您在进入和退出代码块时执行特定的操作,例如打开和关闭文件、建立和关闭数据库连接、获取和释放锁等。上下文管理器常常与 with 语句一起使用,以确保资源在使用后被正确地释放。Python中主要通过两种方法实现:
使用类实现上下文管理器
要创建一个使用类实现的上下文管理器,您需要定义一个类,该类包括 enter 和 exit 方法。enter 方法用于进入代码块前执行的操作,而 exit 方法用于退出代码块后执行的操作。
class ParseFile:def __init__(self, filename, mode):self.filename = filenameself.mode = modedef __enter__(self):self.file = open(self.filename, self.mode)return self.filedef __exit__(self, exc_type, exc_value, traceback):""":param exc_type: 异常类型:param exc_value: 异常值:param traceback: 异常相关的堆栈跟踪信息,堆栈跟踪包括了引发异常的代码路径以及函数调用链:return:"""self.file.close()# 使用上下文管理器打开文件
with ParseFile('data.txt', 'r') as f:print(f.read())
生成器也可以用作上下文管理器
使用@contextmanager 装饰器标记为上下文管理器,yield会把函数定位分成两个部分:yield前面所有代码是在with开始时执行(类似__enter__方法),yield后面的是在with结束时执行(类似__exit__方法)
from contextlib import contextmanager
import timedef adds():for i in range(3):print(i)time.sleep(1)@contextmanager
def timing_context(func):start_time = time.time()try:func()yield 'runtime' # 进入上下文 yield后面的值,就会赋在 with语句的as 后面finally:end_time = time.time()elapsed_time = end_time - start_timeprint(f"Elapsed time: {elapsed_time} seconds")# 使用上下文管理器来测量代码块的执行时间
with timing_context(adds) as msg:# 模拟耗时操作print(msg)# 上下文管理器会自动计算和打印执行时间