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>

  代码的执行顺序是:

  1. with 语句 首先执行 yield 之前的语句,因此打印出 <h1>.
  2. yield 调用会执行 with 语句内部的所有语句,因此打印出 hello 和 world.
  3. 最后执行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的更多相关文章

  1. (转)contextlib — 上下文管理器工具

    原文:https://pythoncaff.com/docs/pymotw/contextlib-context-manager-tool/95 这是一篇社区协同翻译的文章,你可以点击右边区块信息里的 ...

  2. Python 上下文管理器模块--contextlib

    在 Python 处理文件的时候我们使用 with 关键词来进行文件的资源关闭,但是并不是只有文件操作才能使用 with 语句.今天就让我们一起学习 Python 中的上下文管理 contextlib ...

  3. Python标准模块--ContextManager

    1 模块简介 在数年前,Python 2.5 加入了一个非常特殊的关键字,就是with.with语句允许开发者创建上下文管理器.什么是上下文管理器?上下文管理器就是允许你可以自动地开始和结束一些事情. ...

  4. python 安装第三方库,超时报错--Read timed out.

    Traceback (most recent call last): File "/home/xiaoduc/.pyenv/versions/3.5.0/lib/python3.5/site ...

  5. tensorflow由于未初始化变量所导致的错误

     版权声明:本文为博主原创文章,如需转载请注明出处,谢谢. https://blog.csdn.net/qq_38542085/article/details/78742295 初始代码 import ...

  6. python安装pandas模块

    直接安装时报错了 localhost:~ ligaijiang$ pip3 install pandas Collecting pandas Downloading https://files.pyt ...

  7. python-性能测试

    目录: 1.timeit 1.1 在命令后调用timeit 1.2 在代码中使用 1.3 创建计时器实例,通过autorange获得循环次数 1.4 Wall时间和CPU时间 2.profile和cP ...

  8. 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 ...

  9. VS code MacOS 环境搭建

    环境:MacBook Pro 参考博客 为了动手开发AI代码,我需要安装一个VS code. 开始我以为是安装visual studio呢.我装过visual studio2017. VS code是 ...

随机推荐

  1. MySQL多表查询回顾

    ----------------------siwuxie095 MySQL 多表查询回顾 以客户和联系人为例(一对多) 1.内连接 /*内连接写法一*/ select * from t_custom ...

  2. ubuntu 重启显卡报错 nvidia

    1.我装玩显卡以后重启报错了 解决了5个小时才解决,先贴个当时报错的图 第一个图是没有加nomodeset 出先的 当你出现第二个图片的时候证明你离成功不远了 从头开始: 1.开机,出现 ubuntu ...

  3. Java-汉字繁体拼音转换

    import com.github.stuxuhai.jpinyin.ChineseHelper; import com.github.stuxuhai.jpinyin.PinyinFormat; i ...

  4. 启动日志中就出现[java:comp/env/spring.liveBeansView.mbeanDomain] not found这个日志

    今天在做一个dubbo服务端的时候,启动成功,dubbo也注册成功,但是启动日志中就出现[java:comp/env/spring.liveBeansView.mbeanDomain] not fou ...

  5. 关于《Spark快速大数据分析》运行例子遇到的报错及解决

    一.描述 在书中第二章,有一个例子,构建完之后,运行: ${SPARK_HOME}/bin/spark-submit --class com.oreilly.learningsparkexamples ...

  6. (转)Docker镜像中的base镜像理解

    base 镜像有两层含义: 不依赖其他镜像,从 scratch 构建. 其他镜像可以之为基础进行扩展. 所以,能称作 base 镜像的通常都是各种 Linux 发行版的 Docker 镜像,比如 Ub ...

  7. IOS操作系统上执行monkey测试

    IOS操作系统上执行monkey测试 IOS操作系统不像Android系统那么方便,各种限制也比较多,目前我的建议还是直接在模拟器上执行monkey测试.如果需要在真机上面执行,可以参考文档: htt ...

  8. PropertiesConfiguration 修改配置文件的信息,不打乱顺序

    需引入jar包 <!-- https://mvnrepository.com/artifact/commons-configuration/commons-configuration --> ...

  9. javascript总结28 :匿名函数

    1 匿名函数 //匿名函数. // (function (){ // console.log(1); // }) 2  匿名函数作用 //1.直接调用 (function (){ console.lo ...

  10. CodeForces 690D1 The Wall (easy) (判断连通块的数量)

    题意:给定一个图,问你有几个连通块. 析:不用说了,最简单的DFS. 代码如下: #include <bits/stdc++.h> using namespace std; const i ...