笔记-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-朴素贝叶斯
--------------------------------------------------------------------------------------- 本系列文章为<机器 ...
随机推荐
- java技术小白的入门
一.入门书籍 1,疯狂java讲义 2,java编程思想 3,Maven权威指南 4,Spring 3.0就是这么简单 5,Spring技术内幕 6,Spring实战 7,Maven实战 二.入门业务 ...
- [持续更新] Linux基础的重要命令
命令总结:100个左右 mkdir 方法一 [root@localhost ~]# mkdir /test && ls -ld /test 方法二 [root@localhost ~] ...
- div多选控制
此点击按钮,弹出DIV,div内容可以多项选择,点击确定,被选项回填至文本框.功能类似之前写过的一篇日期多选,不过是在其基础上,新增点击页面其他区域,隐藏div功能. 1.css部分代码 .multi ...
- 如何使用Nunit进行测试
如何使用Nunit进行测试(Visual Studio 2017 comminity) 原文:如何使用Nunit进行测试(Visual Studio 2017 comminity) 一.环境 操作系统 ...
- python的元组
Python的元组和列表很相似,只是元组一旦定义就无法修改,比如定义一个学生的元组: names = ('alex','jack') print(names)#('alex', 'jack') pri ...
- 2.eclipse安装
1.进入官网https://www.eclipse.org/ 2.配置工作目录:存放 1.项目代码 2.IDE相关配置信息 3.没有配置tomcat,所以为空.
- 如何在CRM WebClient UI里使用HANA Live Report
1. 使用业务角色ANALYTICSPRO登录SAP CRM WebClient UI: 点击新建按钮创建一个新的HANA live report: 类型选择SHL: 弹出窗口,维护report的名称 ...
- iis 7 操作 .net
下面说一下.NET对IIS7操作.IIS7的操作和IIS5/6(using system.DirectoryServices;使用类DirectoryEntry )有很大的不同,在IIS7里增加了 M ...
- http协议的发展历史
在最早的时候,第一个定稿的http协议是http/0.9版本,在这个版本里面,http协议,它的内容,非常非常的简单 只有一个命令,就是GET 对应的就是我们现在经常用到的get请求,post请求,这 ...
- Java 字符串转码工具类
StringConvertUtils.java package javax.utils; /** * 字符串转码工具类 * * @author Logan * @createDate 2019-04- ...