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. 存储过程中使用事务和try catch

    一.存储过程中使用事务的简单语法 在存储过程中使用事务时非常重要的,使用数据可以保持数据的关联完整性,在Sql server存储过程中使用事务也很简单,用一个例子来说明它的语法格式: 代码 : Cre ...

  2. SQL Server XML变量转为Json文本

    1 -- create function 2 create function [dbo].[fnXmlToJson] (@XmlData xml) 3 returns nvarchar(max) 4 ...

  3. 安装操作系统CentOS-7.x

    一.创建虚拟机 使用VMware Fusion创建虚拟机 二.系统安装 为了统一环境,保证实验的通用性,将网卡名称设置为eth*,不使用CentOS 7默认的网卡命名规则.所以需要在安装的时候,增加内 ...

  4. Jenkins一天中构建多次

    Build after other projects are built:在其他项目触发的时候触发,里面有分为三种情况,也就是其他项目构建成功.失败.或者不稳定的时候触发项目: Poll SCM:定时 ...

  5. Git回滚到历史节点(SourceTree篇)

    转自:http://blog.csdn.net/u010416101/article/details/78142697.https://www.zhihu.com/question/48178380 ...

  6. 908G New Year and Original Order

    传送门 分析 代码 #include<iostream> #include<cstdio> #include<cstring> #include<string ...

  7. select下拉列表

    1.写 <!DOCTYPE html> <html> <head> <title></title> <script language= ...

  8. 44个javascript 变态题解析

    原题来自: javascript-puzzlers 读者可以先去做一下感受感受. 当初笔者的成绩是 21/44… 当初笔者做这套题的时候不仅怀疑智商, 连人生都开始怀疑了…. 不过, 对于基础知识的理 ...

  9. 遍历properties文件

    Properties pro = new Properties();try {    InputStream inStr = ClassLoader.getSystemResourceAsStream ...

  10. java.lang.NoClassDefFoundError: Could not initialize class com解决方案

    编写的时候遇到这样一个bug, java.lang.NoClassDefFoundError: Could not initialize class com 纠结了两天多,但是,没有找到答案,这个问题 ...