contextlib

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()

编写__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这个decorator接受一个generator

在某段代码执行前后自动执行特定代码,也可以用@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语句使用urlopen():

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

它的作用就是把任意对象变为上下文对象,并支持with语句。

contextlib的更多相关文章

  1. RF源码阅读(碎片纪录)-Python积木之contextlib

    参考页面: http://docs.python.org/2/library/contextlib.html contextlib是为了配合with语句来使用的.使用起来更加简洁.本来想写一下,这位同 ...

  2. python contextlib 上下文管理器

    1.with操作符 在python中读写文件,可能需要这样的代码 try-finally读写文件 file_text = None try: file_text = open('./text', 'r ...

  3. 【Python】 上下文管理器和contextlib

    上下文管理器 一直对python中的上下文管理比较迷惑,趁着今天研究SQLAlchemy顺便看了一下,感觉稍微清楚了一点.http://www.cnblogs.com/chenny7/p/421344 ...

  4. python上下文管理器ContextLib及with语句

    http://blog.csdn.net/pipisorry/article/details/50444736 with语句 with语句是从 Python 2.5 开始引入的一种与异常处理相关的功能 ...

  5. Python with/as和contextlib上下文管理使用说明

    with/as 使用open打开过文件的对with/as都已经非常熟悉,其实with/as是对try/finally的一种替代方案. 当某个对象支持一种称为"环境管理协议"的协议时 ...

  6. 一分钟了解contextlib模块

    cobtextlib模块用于简化上下文管理器,其内置装饰漆@contextmanager,我们通过编写一个被contextmanager装饰的generator来简化上下文管理. from conte ...

  7. python常用内建模块 collections,bs64,struct,hashlib,itertools,contextlib,xml

    #  2  collections 是Python内建的一个集合模块,提供了许多有用的集合类. # 2.1 namedtuple #tuple可以表示不变集合,例如,一个点的二维坐标就可以表示成: p ...

  8. contextlib 上下文管理器

    在Python中,读写文件这样的资源要特别注意,必须在使用完毕后正确关闭它们.正确关闭文件资源的一个方法是使用try...finally: try: f = open('/path/to/file', ...

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

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

  10. python之模块contextlib 加强with语句而存在

    # -*- coding: utf-8 -*- #python 27 #xiaodeng #python之模块contextlib,为加强with语句而存在 #特别注意:python3和python2 ...

随机推荐

  1. redis 集群的密码设置

    redis的密码设置有2种方式 1,  这个方法我没试 修改所有Redis集群中的redis.conf文件加入: masterauth passwd123 requirepass passwd123  ...

  2. CodeIgniter 目录结构详解

    1. myshop 2. |-----system 框架程序目录 3. |-----core 框架的核心程序 4. |-----CodeIgniter.php 引导性文件 5. |-----Commo ...

  3. 【AppScan】入门工作原理详解

    AppScan,即 AppScan standard edition.其安装在 Windows 操作系统上,可以对网站等 Web 应用进行自动化的应用安全扫描和测试.Rational AppScan( ...

  4. 【很重要】优秀的常用的js库

    http://lodashjs.com/docs/   常用的各种工具库 sprintf  字符串格式 占位符替换等处理 devices.min.js

  5. 验证是否是正整数,是否是mail,是否是正确的身份证

    /// <summary> /// 通用验证类 /// </summary> class DataValidate { /// <summary> /// 验证正整 ...

  6. FusionChart实现柱状图、饼状图的动态数据显示

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  7. 06-码蚁JavaWeb之Servlet生命周期与基本配置

    学习地址:[撩课-JavaWeb系列1之基础语法-前端基础][撩课-JavaWeb系列2之XML][撩课-JavaWeb系列3之MySQL][撩课-JavaWeb系列4之JDBC][撩课-JavaWe ...

  8. 微信小程序button选中改样式-实现单选/多选

    小程序实现多button单选/多选 红色为选中状态 单选 多选 ①wxss /* pages/button-select/button-select.wxss */ .button_container ...

  9. Springboot简介01

    前言: spring是近几年java中最具有代表而且最为流行的框架,spring是基于aop和IOC的思想,在我们的项目中充当了一个粘合剂的作用,既可以成为对象工厂,来管理我们的controller. ...

  10. golang产生guid

    labix.org/v2/mgo/bson 包虽然是MongoDB的golang实现,其中产生唯一ID的算法是独立的,不依赖MongoDB, 提炼这部分的代码如下:   package main im ...