看着代码又发现了一个奇怪的东西:

    @contextlib.contextmanager
def __call__(self, incoming):
result_wrapper = [] yield lambda: result_wrapper.append(
self._dispatch_and_handle_error(incoming)) if result_wrapper[0] == NotificationResult.HANDLED:
incoming.acknowledge()
else:
incoming.requeue()

contextlib.contextmanager(func)

This function is a decorator that can be used to define a factory function for with statement context managers, without needing to create a class or separate __enter__() and __exit__() methods.

A simple example (this is not recommended as a real way of generating HTML!):

from contextlib import contextmanager

@contextmanager
def tag(name):
print "<%s>" % name
yield
print "</%s>" % name >>> with tag("h1"):
... print "foo"
...
<h1>
foo
</h1>

The function being decorated must return a generator-iterator when called. This iterator must yield exactly one value, which will be bound to the targets in the with statement’s as clause, if any.

At the point where the generator yields, the block nested in the with statement is executed. The generator is then resumed after the block is exited. If an unhandled exception occurs in the block, it is reraised inside the generator at the point where the yield occurred. Thus, you can use a try...except...finally statement to trap the error (if any), or ensure that some cleanup takes place. If an exception is trapped merely in order to log it or to perform some action (rather than to suppress it entirely), the generator must reraise that exception. Otherwise the generator context manager will indicate to the with statement that the exception has been handled, and execution will resume with the statement immediately following the with statement.

也就是说用了contextmanager装饰器的generator,yield语句之前的部分会在进入with的语句块之前执行(generator生成过程,generator函数开始到yield之间的部分),yield的值可以用于with中的as来定义个语句块内的变量。yield的值相当于是__enter__函数的返回,而yield语句后面部分将会在with语句块退出时执行,相当在__exit__函数中执行。

先来试验一下派森大法中generator的执行步骤:

>>> def FakeGenerator():
... print 'iteration begin'
... yield {"msg":'Hello'}
... print 'iteration end'
...
>>> for obj in FakeGenerator():
... print 'get msg:', obj['msg']
...
iteration begin
get msg: Hello
iteration end

也就是说每次迭代中FakeGenerator只会执行到yield语句,然后就获取yield返回的对象给for循环里的语句使用,等到下次迭代时再从yield后面的语句开始执行,真是吊炸天!这样就几乎实现了with语句中对象加了__enter__和__exit__方法时的功能。

不过每次要写个for来代替with显得太土,于是就有了我们的@contextmanager装饰器,它的实现或许是这样的

>>> class FakeGeneratorContext(object):
... def __init__(self, func):
... self.generator_func = func
... self.__exit__ = None
... self.__enter__= None
... self.generator = None
... def __enter__(self):
... self.generator = self.generator_func()
... return self.generator.next()
... def __exit__(self, ext, exv, tb):
... try:
... self.generator.next()
... except StopIteration:
... pass
>>> def fakecontext(func):
... def wrapper():
... context = FakeGeneratorContext(func)
... return context
... return wrapper
...
>>> @fakecontext
... def FakeGenerator():
... print 'iteration begin'
... yield {'msg':'Hello'}
... print 'iteration end'
...
>>> with FakeGenerator() as obj:
... print obj["msg"]
...
iteration begin
Hello
iteration end

有点烦了,再玩下去就和搞Java的一样了

Python contextlib.contextmanager的更多相关文章

  1. python 上下文管理器contextlib.ContextManager

    1 模块简介 在数年前,Python 2.5 加入了一个非常特殊的关键字,就是with.with语句允许开发者创建上下文管理器.什么是上下文管理器?上下文管理器就是允许你可以自动地开始和结束一些事情. ...

  2. Python.with.context-manager

    Context Manager 1. Context Manager简介 "Context managers are a way of allocating and releasing so ...

  3. python contextlib 上下文管理器

    1.with操作符 在python中读写文件,可能需要这样的代码 try-finally读写文件 file_text = None try: file_text = open('./text', 'r ...

  4. 源码剖析@contextlib.contextmanager

    示例 @contextlib.contextmanager def result(a): print('before') yield print('after') 外层装饰源码 包装func函数,真实 ...

  5. Python with/as和contextlib上下文管理使用说明

    with/as 使用open打开过文件的对with/as都已经非常熟悉,其实with/as是对try/finally的一种替代方案. 当某个对象支持一种称为"环境管理协议"的协议时 ...

  6. Python——with语句、context manager类型和contextlib库

    目录 一.with语句 二.上下文管理器 三.contextlib模块 基本概念 上下文管理协议(Context Management Protocol) 包含方法 __enter__() 和 __e ...

  7. Python——常用模块(time/datetime, random, os, shutil, json/pickcle, collections, hashlib/hmac, contextlib)

    1.time/datetime 这两个模块是与时间相关的模块,Python中通常用三种方式表示时间: #时间戳(timestamp):表示的是从1970年1月1日00:00:00开始按秒计算的偏移量. ...

  8. Python 上下文管理器模块--contextlib

    在 Python 处理文件的时候我们使用 with 关键词来进行文件的资源关闭,但是并不是只有文件操作才能使用 with 语句.今天就让我们一起学习 Python 中的上下文管理 contextlib ...

  9. python中关于with以及contextlib的使用

    一般在coding时,经常使用with来打开文件进行文件处理,然后无需执行close方法进行文件关闭. with open('test.py','r' as f: print(f.readline() ...

随机推荐

  1. opencv学习笔记(四)--图像平滑处理

    图像平滑处理的几种常用方法: 均值滤波 归一化滤波 高斯模糊 中值滤波 平滑处理(模糊)的主要目的是去燥声: 不同的处理方式适合不同的噪声图像,其中高斯模糊最常用. 其实最重要的是对图像卷积的核的理解 ...

  2. (C/C++) Link List - C++ 版本

    利用C++寫一個基本的 Link list 練習,功能包含 pint list.CreatList.Insert.Delete.Reverse.Search.Clear.GetLen. 先建立相關的C ...

  3. springcloud微服务 总结一

    一 什么是微服务 译文: 微服务架构是一种架构模式,它提倡将单一应用程序划分成一组小的服务,服务之间互相协调.互相配合,为用户提供最终价值.每个服务运行在其独立的进程中,服务与服务间采用轻量级的通信机 ...

  4. 【原创】nginx入门

    一.简介 Nginx (engine x) 是一个高性能的HTTP和反向代理服务,也是一个IMAP/POP3/SMTP服务.Nginx是由伊戈尔·赛索耶夫为俄罗斯访问量第二的Rambler.ru站点( ...

  5. Training set,Gallery set 和Probe set的区别

    这段时间看了CVPR2017的这篇论文”SphereFace:Deep Hypersphere Embedding for Face Recognition" 里面有提到Probe set, ...

  6. CF D - Beautiful Graph(dfs 染色问题吧)给你一个图,每个节点可以赋值1,2,3三种数字,相邻的节点的和必须是奇数,问有多少中方法。

    题意: 给你一个图,每个节点可以赋值1,2,3三种数字,相邻的节点的和必须是奇数,问有多少中方法. 分析: 很容易就可以发现如果这个图中是有奇数的环的话,那这是肯定不行的 ,否则这个环的贡献是为2^s ...

  7. css 之 BFC

    1,定义 BFC为块级格式化上下文,也就是一块区域内的封闭空间,里面元素无论怎么样,都不会影响外部元素. 2,触发条件 html 根元素 display的值为 inline-block.table-c ...

  8. C#工具类之XmlNode扩展类

    using System; using System.Linq; using System.Xml; /// <summary> /// XmlNodeHelper /// </su ...

  9. [转] log4j-over-slf4j与slf4j-log4j12共存stack overflow异常分析

    [From] http://www.tuicool.com/articles/INveIf 注:下文中的“桥接”.“转调”.“绑定”等词基本都是同一个概念. log4j-over-slf4j和slf4 ...

  10. rancher初级(搭建+基本操作+web应用部署)

    Rancher搭建 首先rancher需要安装了docker的linux环境,我的系统版本为 在docker的基础上启动rancher服务器,Rancher 服务器是一个 Docker image,所 ...