Python实现上下文管理器的方法
作者:David Beazley 时间:2021-06-22 17:31:15
问题
你想自己去实现一个新的上下文管理器,以便使用with语句。
解决方案
实现一个新的上下文管理器的最简单的方法就是使用 contexlib 模块中的 @contextmanager 装饰器。 下面是一个实现了代码块计时功能的上下文管理器例子:
import time
from contextlib import contextmanager
@contextmanager
def timethis(label):
start = time.time()
try:
yield
finally:
end = time.time()
print('{}: {}'.format(label, end - start))
# Example use
with timethis('counting'):
n = 10000000
while n > 0:
n -= 1
在函数 timethis()
中,yield
之前的代码会在上下文管理器中作为 __enter__()
方法执行, 所有在 yield
之后的代码会作为 __exit__()
方法执行。 如果出现了异常,异常会在yield语句那里抛出。
下面是一个更加高级一点的上下文管理器,实现了列表对象上的某种事务:
@contextmanager
def list_transaction(orig_list):
working = list(orig_list)
yield working
orig_list[:] = working
这段代码的作用是任何对列表的修改只有当所有代码运行完成并且不出现异常的情况下才会生效。 下面我们来演示一下:
>>> items = [1, 2, 3]
>>> with list_transaction(items) as working:
... working.append(4)
... working.append(5)
...
>>> items
[1, 2, 3, 4, 5]
>>> with list_transaction(items) as working:
... working.append(6)
... working.append(7)
... raise RuntimeError('oops')
...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
RuntimeError: oops
>>> items
[1, 2, 3, 4, 5]
>>>
讨论
通常情况下,如果要写一个上下文管理器,你需要定义一个类,里面包含一个 __enter__() 和一个 __exit__() 方法,如下所示:
import time
class timethis:
def __init__(self, label):
self.label = label
def __enter__(self):
self.start = time.time()
def __exit__(self, exc_ty, exc_val, exc_tb):
end = time.time()
print('{}: {}'.format(self.label, end - self.start))
尽管这个也不难写,但是相比较写一个简单的使用 @contextmanager
注解的函数而言还是稍显乏味。
@contextmanager
应该仅仅用来写自包含的上下文管理函数。 如果你有一些对象(比如一个文件、网络连接或锁),需要支持 with
语句,那么你就需要单独实现 __enter__()
方法和 __exit__()
方法。
来源:https://python3-cookbook.readthedocs.io/zh_CN/latest/c09/p22_define_context_managers_the_easy_way.html
标签:Python,上下文管理器
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python爬虫框架Scrapy安装使用步骤
2022-02-23 13:49:09
Python深度学习pytorch神经网络多层感知机简洁实现
2021-08-20 17:37:43
![](https://img.aspxhome.com/file/2023/7/107477_0s.png)
数字人组件反写[asp组件开发实例5]
2009-06-09 13:23:00
![](https://img.aspxhome.com/file/UploadPic/20093/9/20093918286639s.gif)
Python多线程结合队列下载百度音乐的方法
2022-12-01 11:43:18
Python下划线5种含义代码实例解析
2023-11-19 04:25:59
![](https://img.aspxhome.com/file/2023/3/87583_0s.jpg)
python 内置函数filter
2023-01-07 21:53:37
Python3.8安装tensorflow的简单方法步骤
2021-03-11 23:31:42
![](https://img.aspxhome.com/file/2023/3/81663_0s.png)
python 类对象的析构释放代码演示
2023-11-22 18:54:53
ExpiresAbsolute 属性
2008-05-05 12:49:00
python根据用户需求输入想爬取的内容及页数爬取图片方法详解
2022-12-21 16:31:19
![](https://img.aspxhome.com/file/2023/4/69024_0s.png)
详解如何用Python实现感知器算法
2023-11-02 13:32:20
![](https://img.aspxhome.com/file/2023/3/91973_0s.png)
python绘制漏斗图步骤详解
2021-06-17 22:57:57
![](https://img.aspxhome.com/file/2023/7/101247_0s.png)
使用FastCGI部署Python的Django应用的教程
2021-08-24 20:56:54
微信小程序开发之获取用户手机号码(php接口解密)
2023-11-15 03:34:59
![](https://img.aspxhome.com/file/2023/3/84863_0s.png)
python通过pil模块获得图片exif信息的方法
2021-08-26 14:31:21
scrapy-redis源码分析之发送POST请求详解
2021-05-19 05:24:03
Python tkinter实现简单加法计算器代码实例
2024-01-03 03:58:49
![](https://img.aspxhome.com/file/2023/2/108042_0s.png)
PyTorch+LSTM实现单变量时间序列预测
2023-09-23 02:58:05
![](https://img.aspxhome.com/file/2023/5/92445_0s.jpg)
一行Python代码制作动态二维码的实现
2023-11-04 02:32:19
![](https://img.aspxhome.com/file/2023/7/78847_0s.jpg)
浅谈Python中chr、unichr、ord字符函数之间的对比
2022-02-27 16:02:58