笔记-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. python反爬之网页局部刷新1

    # ajax动态加载网页 # 怎样判断一个网页是不是动态加载的呢? # 查看网页源代码,如果源码中没有你要的数据,尝试访问下一页,当你点击下一页的时候,整个页面没有刷新, 只是局部刷新了,很大的可能是 ...

  2. easyui datagrid 表格中操作栏 按钮图标不显示

    jQuery EasyUI动态添加控件或者ajax加载页面后不能自动渲染 解决办法: 使用解析器 Parser(解析器) $.parser.parse();       // 解析所有页面 $.par ...

  3. ASP.NET MVC 音乐商店 - 2.控制器

    在典型的 Web 应用中,用户请求的 URL 地址通常映射到保存在网站中的文件上,例如,当用户请求 /Products.aspx 的时候,或者 /Products.php 的时候,很可能是在通过处理 ...

  4. SharePoint 2010 究竟需要占用多少服务器资源?

    SharePoint 安装目录(即SharePoint Root)大约 300M 磁盘空间. SharePoint Config 数据库,60M. Admin Center 数据库,100M. 默认安 ...

  5. springboot项目搭建:结构和入门程序

    Spring Boot 推荐目录结构 代码层的结构 根目录:com.springboot 1.工程启动类(ApplicationServer.java)置于com.springboot.build包下 ...

  6. vos2009如何设置客户自助密码

    1.  VOS2009 账户管理——>网关管理——>密码:就是客户的自助登陆密码 2.  VOS3000 Vos3000里配置密码和自助密码分开 3.  登陆测试 浏览器输入http:// ...

  7. JavaScript 如何编写计算器

    1.JavaScript制作计算器 <!DOCTYPE html> <html> <head> <meta charset="UTF-8" ...

  8. 用户表单事件(focus事件)

    以前做用户系统的时候经常用到表单验证,正则表达式事件来处理和绑定事件和进行事件,这里说的其实只是一小部分,也不是很值得写,但是今天遇到了还是写一下,毕竟基础还是蛮重要的,就算懂的童鞋,巩固一下也是好的 ...

  9. C4C销售订单中业务伙伴的自动决定功能Partner determination procedure

    例子:我新建一个Sales Order,account 字段选择ID为1001的Account:Porter LLC 创建成功后,观察这个Sales Order的Involved Party里,Bil ...

  10. Linux同步目录 保留文件修改时间和权限 rsync

    scp copy文件夹的时候,会强行覆盖文件,导致增量同步的时候不方便,而rsync则能很好解决这个问题. rsync -avz ubuntu@192.168.1.208:/home/ubuntu/m ...