笔记-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-朴素贝叶斯
--------------------------------------------------------------------------------------- 本系列文章为<机器 ...
随机推荐
- js之正则表达式(RegExp对象)
先看一个很有意思的例子: 用字面量的方式定义了一个正则表达式 /\w/g,再重复匹配字符串 ‘ab’ 的时候,出现了结果不唯一的现象. 很多新手都对这种现象感到困惑,难道是正则表达式不稳定吗? 接下来 ...
- 树checkbox选择jquery实例
<!DOCTYPE html> <html> <head> <title></title> <script src="htt ...
- u-boot分析(六)----时钟初始化
u-boot分析(六) 上篇博文我们按照210的启动流程,分析到了关闭看门狗,今天我们继续按照u-boot的启动流程进行分析,今天我们会主要分析时钟的初始化. 今天我们会用到的文档: 1. ...
- seleniumCSS用法
http://sauceio.com/index.php/2009/10/selenium-tip-of-the-week-start-improving-your-locators/ http:// ...
- 分享一个JDK1.8丢失数字精度的案例
差异出现在 DigitList.java的 round() 方法处理上: 1.6: 1.8: 根据设置规则消除无需显示的数字时,JDK1.8 新增了一个二进制数向ASCII码转换的过程如下: 从而导致 ...
- jstl Maven 依赖导致的 Jar 包冲突
概述 Jar 包冲突是日常开发过程中,时常会遇到的问题.本文介绍由 jstl 的 Maven 依赖导致的 Jar 包冲突问题,以及对应的解决方法. jstl 的 Maven 依赖配置 <depe ...
- user(),current_user()函数的区别
user() 表示当前的登录用户 current_user() 表示对应于mysql.user表里对应的账号.
- 用dynamic的方式来转换Json对象
来自这里:http://stackoverflow.com/questions/3142495/deserialize-json-into-c-sharp-dynamic-object If you ...
- Spring Security 之Session管理配置
废话不多说,直接上代码.示例如下: 1. 新建Maven项目 session 2. pom.xml <project xmlns="http://maven.apache.o ...
- 使用nssm将bat文件注册为windows service (eg:solr, nodejs)
nssm下载:http://pan.baidu.com/s/1sjAEevj _install.bat @echo off Set BasePath=D:\Tools %BasePath%\nssm- ...