笔记-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的更多相关文章

  1. 笔记-python -asynio

    笔记-python -asynio 1.      简介 asyncio是做什么的? asyncio is a library to write concurrent code using the a ...

  2. 笔记-python操作mysql

    笔记-python操作mysql 1.      开始 1.1.    环境准备-mysql create database db_python; use db_python; create tabl ...

  3. 笔记-python异常信息输出

    笔记-python异常信息输出 1.      异常信息输出 python异常捕获使用try-except-else-finally语句: 在except 语句中可以使用except as e,然后通 ...

  4. 笔记-python lib-pymongo

    笔记-python lib-pymongo 1.      开始 pymongo是python版的连接库,最新版为3.7.2. 文档地址:https://pypi.org/project/pymong ...

  5. 笔记-python tutorial-9.classes

    笔记-python tutorial-9.classes 1.      Classes 1.1.    scopes and namespaces namespace: A namespace is ...

  6. MongoDB学习笔记:Python 操作MongoDB

    MongoDB学习笔记:Python 操作MongoDB   Pymongo 安装 安装pymongopip install pymongoPyMongo是驱动程序,使python程序能够使用Mong ...

  7. 机器学习实战笔记(Python实现)-08-线性回归

    --------------------------------------------------------------------------------------- 本系列文章为<机器 ...

  8. 机器学习实战笔记(Python实现)-05-支持向量机(SVM)

    --------------------------------------------------------------------------------------- 本系列文章为<机器 ...

  9. 机器学习实战笔记(Python实现)-04-Logistic回归

    --------------------------------------------------------------------------------------- 本系列文章为<机器 ...

  10. 机器学习实战笔记(Python实现)-03-朴素贝叶斯

    --------------------------------------------------------------------------------------- 本系列文章为<机器 ...

随机推荐

  1. MyBatis中sql语句

    一.select <!-- 查询学生,根据id --> <select id="getStudent" parameterType="String&qu ...

  2. element-ui打包的坑爹之处 !!!必看三遍!!!

    最近笔者打包element-ui出现如下问题: ERROR in static/js/0.4cad92088cb8dc6e7afd.js from UglifyJs Unexpected token: ...

  3. 笨办法学Python(十八)

    习题 18: 命名.变量.代码.函数 标题包含的内容够多的吧?接下来我要教你“函数(function)”了!咚咚锵!说到函数,不一样的人会对它有不一样的理解和使用方法,不过我只会教你现在能用到的最简单 ...

  4. 洛谷 P3905 道路重建

    题目描述 从前,在一个王国中,在n个城市间有m条道路连接,而且任意两个城市之间至多有一条道路直接相连.在经过一次严重的战争之后,有d条道路被破坏了.国王想要修复国家的道路系统,现在有两个重要城市A和B ...

  5. IIS7 http自动跳转到https(通过编辑Web.config实现)

    本文摘自:https://www.cnblogs.com/wxbug/p/7054972.html 1.下载安装URL重写模块:Microsoft URL Rewrite Module 32位:htt ...

  6. LA 2957 最大流,最短时间,输出路径

    题目链接:https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&category=1 ...

  7. clear:both;和overflow:hidden;的应用理解。

    摘自cbwcwy 前辈: clear是子模块之间限定的,如下:<div id="a">    <div id="1"></div& ...

  8. a=a+(a++);b=b+(++b);计算顺序,反汇编

    a=a+(a++); 013913BC mov eax,dword ptr [a] 013913BF add eax,dword ptr [a] 013913C2 mov dword ptr [a], ...

  9. YSlow的安装与说明文档

    yslow官网 http://yslow.org/ 很明显起这个名字是说why slow 为什么这么慢,理所当然是为当前网页进行检测 借百度的 什么是YSlow? YSlow是yahoo发布的一款基于 ...

  10. JavaScript正则(一)

    1.字符组: ^  $ 说的是开始位置和结束位置,在JS中,既表示字符串的起始位置和结束位置,也表示行的起始位置和结束位置 console.log(/^\d$/.test('2')); // true ...