笔记-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. 在使用angular和swiper插件中的一些问题

    在使用angular获取swiper图片的时候swiper就不会轮播. 解决方法: 1.使用计时器的方法,不是最优 settimeOut(function(){ mySwiper = new Swip ...

  2. redis在Windows下以后台服务一键搭建哨兵(主从复制)模式(多机)

    redis在Windows下以后台服务一键搭建哨兵(主从复制)模式(多机) 一.概述 此教程介绍如何在windows系统中多个服务器之间,布置redis哨兵模式(主从复制),同时要以后台服务的模式运行 ...

  3. Servlet是线程安全的吗?

    Servlet不是线程安全的. 要解释为什么Servlet为什么不是线程安全的,需要了解Servlet容器(即Tomcat)使如何响应HTTP请求的. 当Tomcat接收到Client的HTTP请求时 ...

  4. C#对bat脚本文件的操作示例

    实现C#操作bat脚本文件 using System;using System.Collections.Generic;using System.ComponentModel;using System ...

  5. LDAP 在ubuntu14.04下的安装配置install and configure

    https://help.ubuntu.com/lts/serverguide/openldap-server.html if error occurs in reinstall, try this: ...

  6. jquery对checkbox的操作汇总

    1.全选 $("#btn1").click(function(){ $("input[name='checkbox']").attr("checked ...

  7. webpack整体了解

    一.下载 新建一个文件夹,在cmd中npm init->npm install->npm install webpack --save-dev 下载完成之后,新建一个webpack.con ...

  8. IOS 公司标示和方向域名

    1. 公司标示使用反向域名========================================正向域名 www.baidu.com 用来标示一台网络主机反向域名 cn.itcast.Myd ...

  9. POJ-3187 Backward Digit Sums---枚举全排列

    题目链接: https://vjudge.net/problem/POJ-3187 题目大意: 输入n,sum,求1~n的数,如何排列之后,相邻两列相加,直到得出最后的结果等于sum,输出1~n的排列 ...

  10. jQuery序列化表单为JSON对象

    <form id="myform"> <table> <tr> <td>姓名:</td> <td> < ...