笔记-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-朴素贝叶斯
--------------------------------------------------------------------------------------- 本系列文章为<机器 ...
随机推荐
- lnmp架构-负载均衡
一.几个基本概念 1.pv 值 pv 值(page views):页面的浏览量 概念:一个网站的所有页面,在一天内,被浏览的总次数.(大型网站通常是上千万的级别) 2.uv值 uv值(unique v ...
- CSS中的样式层叠机制Cascade
CSS中的样式层叠机制Cascade 一.样式冲突 样式冲突是CSS渲染过程要解决的一个关键问题,样式冲突主要由两个原因造成: 元素包含了不同对象所赋予的样式:浏览器.用户.作者.其中,浏览器样式 ...
- better-scroll 遇到的问题 3 (transition-group 相关)
今天在使用vue动画 transition-group 和 better-scroll 的时候,出现了下拉列表不能滚动的问题. 问题描述: 我写了一个scroll的基础组件,组件接受一个data参数, ...
- XCode 如何真机运行别人的demo项目
iOS应用安装到真机需要证书和mobileprovision 文件,拿到别人的项目 是没有这些的 ,也就运行不起来. 要想运行起来, 需要选中项目, target - > 修改 bundlei ...
- Spring Cloud入门程序
本文手把手教你,做出第一个Spring Cloud程序,Eureka的简单入门使用 1.创建Spring Starter Project工程 点击next,添加项目名 2.引入Spring Cloud ...
- 学习笔记_TCP编程,服务端
public void startTcpService(String ip) { try { InetAddress ipAddress = InetAddress.getByName(ip); tc ...
- Linux下安装部署RabbitMQ
在写正文之前先啰嗦几句,RabbitMQ(消息队列)的安装让我费了半天劲啊!足足折腾了2天,最后写下这篇文章总结下,其实很简单,但是你找不到错在哪个环节就会费很多无用功,如果你也遇到了安装erl后 怎 ...
- 微信的 rpx
微信小程序新单位rpx与自适应布局 rpx是微信小程序新推出的一个单位,按官方的定义,rpx可以根据屏幕宽度进行自适应,在rpx出现之前,web页面的自适应布局已经有了多种解决方案,为什么微信还捣 ...
- flex布局-常用布局
在使用flex布局,老是需要去查资料,很多常用的,知道大概,可还是需要去过一遍,这里记录一下几个常用的flex布局 一个div,内容垂直居中 html <div className='topHe ...
- 转:深入浅出spring IOC中四种依赖注入方式
转:https://blog.csdn.net/u010800201/article/details/72674420 深入浅出spring IOC中四种依赖注入方式 PS:前三种是我转载的,第四种是 ...