笔记-python-lib-contextlib
笔记-python-lib-contextlib
1. contextlib
with 语句很好用,但不想每次都写__enter_-和__exit__方法;
py标准库也为此提供了工具模块contextlib
模块提供的功能有很多,重点说一下contextmanager
2. contextmanager
它提供了一个简单的上下文环境
简单使用:
from contextlib import contextmanager
@contextmanager
def make_open_context(filename, mode):
fp = open(filename, mode)
try:
yield fp
finally:
fp.close()
with make_open_context('i002.txt','a') as fi:
fi.write('hello ')
不用创建类和写__enter__,__exit__方法。
2.1. 代码释义
def contextmanager(func):
"""@contextmanager decorator.
Typical usage:
@contextmanager
def some_generator(<arguments>):
<setup>
try:
yield <value>
finally:
<cleanup>
This makes this:
with some_generator(<arguments>) as <variable>:
<body>
equivalent to this:
<setup>
try:
<variable> = <value>
<body>
finally:
<cleanup>
"""
@wraps(func)
def helper(*args, **kwds):
return _GeneratorContextManager(func, args, kwds)
return helper
contextmanager是一个装饰器函数,去掉注释,实际上是返回一个中间函数helper,helper返回的则是一个上下文管理器,具体的实现可以看下代码。
2.2. _GeneratorContextManager(func, args, kwds)
前序准备工作非常简单,主要是后续清理代码比较多。
def __enter__(self):
try:
return next(self.gen)
except StopIteration:
raise RuntimeError("generator didn't yield") from None
def __exit__(self, type, value, traceback):
if type is None:
try:
next(self.gen)
except StopIteration:
return False
else:
raise RuntimeError("generator didn't stop")
else:
if value is None:
# Need to force instantiation so we can reliably
# tell if we get the same exception back
value = type()
try:
self.gen.throw(type, value, traceback)
except StopIteration as exc:
# Suppress StopIteration *unless* it's the same exception that
# was passed to throw(). This prevents a StopIteration
# raised inside the "with" statement from being suppressed.
return exc is not value
except RuntimeError as exc:
# Don't re-raise the passed in exception. (issue27122)
if exc is value:
return False
# Likewise, avoid suppressing if a StopIteration exception
# was passed to throw() and later wrapped into a RuntimeError
# (see PEP 479).
if type is StopIteration and exc.__cause__ is value:
return False
raise
except:
# only re-raise if it's *not* the exception that was
# passed to throw(), because __exit__() must not raise
# an exception unless __exit__() itself failed. But throw()
# has to raise the exception to signal propagation, so this
# fixes the impedance mismatch between the throw() protocol
# and the __exit__() protocol.
#
if sys.exc_info()[1] is value:
return False
raise
raise RuntimeError("generator didn't stop after throw()")
3. 参考文档
参考文档:https://docs.python.org/3/library/contextlib.html?highlight=contextlib#module-contextlib
笔记-python-lib-contextlib的更多相关文章
- 笔记-python -asynio
笔记-python -asynio 1. 简介 asyncio是做什么的? asyncio is a library to write concurrent code using the a ...
- 笔记-python操作mysql
笔记-python操作mysql 1. 开始 1.1. 环境准备-mysql create database db_python; use db_python; create tabl ...
- 笔记-python异常信息输出
笔记-python异常信息输出 1. 异常信息输出 python异常捕获使用try-except-else-finally语句: 在except 语句中可以使用except as e,然后通 ...
- 笔记-python lib-pymongo
笔记-python lib-pymongo 1. 开始 pymongo是python版的连接库,最新版为3.7.2. 文档地址:https://pypi.org/project/pymong ...
- 笔记-python tutorial-9.classes
笔记-python tutorial-9.classes 1. Classes 1.1. scopes and namespaces namespace: A namespace is ...
- MongoDB学习笔记:Python 操作MongoDB
MongoDB学习笔记:Python 操作MongoDB Pymongo 安装 安装pymongopip install pymongoPyMongo是驱动程序,使python程序能够使用Mong ...
- 机器学习实战笔记(Python实现)-08-线性回归
--------------------------------------------------------------------------------------- 本系列文章为<机器 ...
- 机器学习实战笔记(Python实现)-05-支持向量机(SVM)
--------------------------------------------------------------------------------------- 本系列文章为<机器 ...
- 机器学习实战笔记(Python实现)-04-Logistic回归
--------------------------------------------------------------------------------------- 本系列文章为<机器 ...
- 机器学习实战笔记(Python实现)-03-朴素贝叶斯
--------------------------------------------------------------------------------------- 本系列文章为<机器 ...
随机推荐
- SpringCloud的学习记录(3)
这一章节讲搭建config-server的项目. 在我们生成的Demo项目上右键点击New->Module->spring Initializr, 然后next, 填写Group和Arti ...
- python字符转码
字符的编码与转码 demo UTF-8 转GBK python2.7 默认编码ASCII 没有转Unicode 直接转GBK 1 .系统的默认编码是ASCII , 程序的指定编码是UTF-8,在enc ...
- Bloom Filter (海量数据处理)
什么是Bloom Filter 先来看这样一个爬虫相关问题:文件A中有10亿条URL,每条URL占用64字节,机器的内存限制是4G,现有一个URL,请判断它是否存在于文件A中(爬过的URL无需再爬). ...
- SINAMICS S120 Parking axis设置,安转拆除或屏蔽电机
1) P897 Parking axis selection 此参数可以连接到周期通讯的报文中(PZD) 2) 标准报文111中,已经连接此参数
- Android_ListView适配器
ListView如何优化 复用convertView缓存(减少ListView绘制). 自定义静态类ViewHolder(减少findViewById次数),通过setTag().getTag()获取 ...
- v-for的深层用法
为了提升循环的性能,我们会给循环加上一个唯一的key值,这个key值一定是唯一的 <div id='root'> <div v-for='(item,index) of list' ...
- spring依赖注入(转)
转自:https://blog.csdn.net/taijianyu/article/details/2338311/ Spring 能有效地组织J2EE应用各层的对象.不管是控 制层的Action对 ...
- 2018.8.6 学习 log4j.properties 配置文件
配置文件的话第一步当然是解决乱码问题 Eclipse中properties文件中文乱码解决方式 打开eclipse的properties文件时你会发现,其中部分中文注释乱码了,下面将写出如何设置pro ...
- 2017.10.27 C语言精品集
第一章 程序设计和C语言 1.1 什么是计算机程序? @ ······ 所谓程序,就是一组计算机能识别和执行的指令.每一条指令使计算机执行特定的操作. 计算机的一切操作都是由程序控制的.所以计算机的本 ...
- HTTP的DELETE方法Body传递参数问题解决
理论上,Delete method是通过url传递参数的,如果使用body传递参数呢? 前提: 使用HttpClient发送http请求 问题: httpDelete对象木有setEntity方法 解 ...