Python3之 contextlib
Python中当我们们打开文本时,通常会是用with语句,with语句允许我们非常方便的使用资源,而不必担心资源没有关闭。
with open('/path/filename', 'r') as f:
f.read()
然而,并不是只有open()函数返回fp对象才能使用 with 语句。实际上,任何对象,只要正确实现上下文管理,就可以使用with语句。实现上下文管理是通过 __enter__ 和 __exit__ 这两个方法实现的。例如,下面的class实现了这两个方法:
class Query(object):
def __init__(self, name):
self.name = name
def __enter__(self):
print('Begin')
return self
def __exit__(self, exc_type, exc_value, traceback):
if exc_type:
print('Error')
else:
print('End')
def query(self):
print('Query info about %s...' % self.name)
这样我们可以把自己写的资源对象用于 with 语句。
with Query('Bob') as q:
q.query()
@contextmanager
编写 __enter__ 和 __exit__ 仍然很繁琐,因此Python的标准库 contextlib 提供了更简单的写法,上面的代码可以改写为:
from contextlib import contextmanager
class Query(object):
def __init__(self, name):
self.name = name
def query(self):
print('Query info about %s...' % self.name)
@contextmanager
def create_query(name):
print('Begin')
q = Query(name)
yield q
print('End')
@contextmanager 这个装饰器接受一个 generator,用 yield 语句把 with ... as var 把变量输出出去,然后,with 语句就可以正常的工作了:
with create_query('Bob') as q:
q.query()
很多时候,我们希望在某段代码执行前后自动执行特定代码,也可以用 @contextmanager实现。
@contextmanager
def tag(name):
print("<%s>" % name)
yield
print("</%s>" % name) with tag("h1"):
print("hello")
print("world")
上述代码执行结果:
<h1>
hello
world
</h1>
代码的执行顺序是:
- with 语句 首先执行 yield 之前的语句,因此打印出 <h1>.
- yield 调用会执行 with 语句内部的所有语句,因此打印出 hello 和 world.
- 最后执行yield之后的语句,打印出 </h1>.
@closing
如果一个对象没有实现上下文,就不能使用 with 语句,但是可以用 closing() 来把对象变为上下文对象。
from contextlib import closing
from urllib.request import urlopen with closing(urlopen('https://www.python.org')) as page:
for line in page:
print(line)
closing 也是一个经过 @contextmanager 装饰的generator
@contextmanager
def closing(thing):
try:
yield thing
finally:
thing.close()
它的作用就是把任意对象变为上下文对象,并支持 with语句。
本文引用于廖雪峰的博客
Python3之 contextlib的更多相关文章
- (转)contextlib — 上下文管理器工具
原文:https://pythoncaff.com/docs/pymotw/contextlib-context-manager-tool/95 这是一篇社区协同翻译的文章,你可以点击右边区块信息里的 ...
- Python 上下文管理器模块--contextlib
在 Python 处理文件的时候我们使用 with 关键词来进行文件的资源关闭,但是并不是只有文件操作才能使用 with 语句.今天就让我们一起学习 Python 中的上下文管理 contextlib ...
- Python标准模块--ContextManager
1 模块简介 在数年前,Python 2.5 加入了一个非常特殊的关键字,就是with.with语句允许开发者创建上下文管理器.什么是上下文管理器?上下文管理器就是允许你可以自动地开始和结束一些事情. ...
- python 安装第三方库,超时报错--Read timed out.
Traceback (most recent call last): File "/home/xiaoduc/.pyenv/versions/3.5.0/lib/python3.5/site ...
- tensorflow由于未初始化变量所导致的错误
版权声明:本文为博主原创文章,如需转载请注明出处,谢谢. https://blog.csdn.net/qq_38542085/article/details/78742295 初始代码 import ...
- python安装pandas模块
直接安装时报错了 localhost:~ ligaijiang$ pip3 install pandas Collecting pandas Downloading https://files.pyt ...
- python-性能测试
目录: 1.timeit 1.1 在命令后调用timeit 1.2 在代码中使用 1.3 创建计时器实例,通过autorange获得循环次数 1.4 Wall时间和CPU时间 2.profile和cP ...
- celery 4.1下报kombu.exceptions.EncodeError: Object of type 'bytes' is not JSON serializable 处理方式
#python代码如下 from celery import Celeryimport subprocess app = Celery('tasks', broker='redis://localho ...
- VS code MacOS 环境搭建
环境:MacBook Pro 参考博客 为了动手开发AI代码,我需要安装一个VS code. 开始我以为是安装visual studio呢.我装过visual studio2017. VS code是 ...
随机推荐
- yaml文件转properties和properties转yaml
首先要引入依赖 <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artif ...
- 知方可补不足~Sqlserver中的几把锁和.net中的事务级别 回到目录
当数据表被事务锁定后,我们再进行select查询时,需要为with(锁选项)来查询信息,如果不加,select将会被阻塞,直到锁被释放,下面介绍几种SQL的锁选项 SQL的几把锁 NOLOCK(不加锁 ...
- 276. Paint Fence篱笆涂色
[抄题]: There is a fence with n posts, each post can be painted with one of the k colors. You have to ...
- leetcode - 3、Longest Substring Without Repeating Characters
题目链接:https://leetcode.com/problems/longest-substring-without-repeating-characters/description/ 题目要求: ...
- IntelliJ IDEA 安装
1.在终端输入sudo vim /private/etc/hosts 2.在打开的hosts文件中,在尾行添加 0.0.0.0 account.jetbrains.com 3.去网站http://id ...
- 最大公约数(gcd)和 最小公倍数(lcm)——辗转相除法
辗转相除法(又称欧几里得算法)是求最大公因数的算法 要求a,b的最大公约数(a>b),我们可以递归地求b,a%b的最大公约数,直到其中一个数变成0,这时另一个数就是a,b的最大公约数. C++实 ...
- [随笔]CENTOS7更换YUM源为163源(记录一下以防忘记)
2016年2月16日,最新163源变更后的更新方法: 访问地址为:http://mirrors.163.com/.help/centos.html 首先备份源: mv /etc/yum.repos.d ...
- Jsp 的映射
Jsp 的映射 Jsp 的映射 Jsp最佳实践 不管是jsp还是Servlet,虽然都可以开发动态Web资源,但是这两门 技术的各自特点,在长期的软件实践中,人们逐渐的把servlet作为 web应用 ...
- STS 闪退
# # A fatal error has been detected by the Java Runtime Environment: # # EXCEPTION_ILLEGAL_INSTRUCTI ...
- 【扫盲贴】为什么屏幕分辨率是 640x480
本文原地址:http://www.easyx.cn/skills/View.aspx?id=172 常见的屏幕分辨率很奇怪,为什么总用一些不零不整的数字?比如以前最常见的分辨率是 640x480,当初 ...