笔记-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. 正则表达式 \w \d 的相关解读

    在查阅很多相关正则的描述之后,发现对于\w 的释义都是指包含大 小写字母数字和下划线 相当于([0-9a-zA-Z]) (取材于经典教程 正则表达式30分钟入门教程) 但是在实际使用中发现并不是这么回 ...

  2. TX Text Control X10新特性之图像占位符合并

    文档处理控件TX Text Control即将发布的X10版本,将升级重点还是放到了其比较优势的流式布局报表设计和生成上.慧都获得了来自其开发商Text Control GmbH公司的一手资料,迫不及 ...

  3. Implementation with Java

    Implementation with Java From:http://jcsc.sourceforge.net In general, follow the Sun coding conventi ...

  4. Can't connect to any repository.Read timed out after 30,000 ms

    解决方法:

  5. char 与 signed char 和 unsigned char三者之间的关系

    # char 与 signed char 和 unsigned char三者之间的关系 三者都占用 1个字节,即 8 bit signed char取值范围(-128, 127) unsigned c ...

  6. IOS NSOperationQueue(线程 封装操作)

    #import "HMViewController.h" @interface HMViewController () @end @implementation HMViewCon ...

  7. Linux MySQL单实例源码编译安装5.5.32

    cmake软件 tar -zxvf cmake-2.8.8.tar.gz cd cmake-2.8.8 ./bootstrap make make install cd ../   依赖包 yum i ...

  8. Android(java)学习笔记62:android.intent.action.MAIN 与 android.intent.category.LAUNCHER 理解

    1. 先看看网路上的说法: android.intent.action.MAIN 决定应用程序最先启动的 Activity android.intent.category.LAUNCHER 决定应用程 ...

  9. 广搜,深搜,单源最短路径,POJ(1130),ZOJ(1085)

    题目链接: http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=85 http://poj.org/problem?id=1130 这 ...

  10. BFS变换素数,POJ(3126)

    题目链接:http://poj.org/problem?id=3126 解题报告: #include <iostream> #include <queue> #include ...