创建充当装饰器和上下文管理器的api。

contextdecorator的Python项目详细描述


如果您是库或框架的创建者,那么能够创建 可以将用作装饰器或上下文管理器的api。

ContextDecorator模块是添加到 contextlib module英寸 Python3.2。ContextDecorator与Python2.4+一起工作,包括Python3。

ContextDecorator继承的上下文管理器必须实现 __enter____exit__正常。 __exit__ 即使用作装饰器,也保留其可选异常处理。

示例:

from contextdecorator import ContextDecorator

class mycontext(ContextDecorator):
   def __enter__(self):
      print 'Starting'
      return self

   def __exit__(self, *exc):
      print 'Finishing'
      return False

>>> @mycontext()
... def function():
...    print 'The bit in the middle'
...
>>> function()
Starting
The bit in the middle
Finishing

>>> with mycontext():
...    print 'The bit in the middle'
...
Starting
The bit in the middle
Finishing

已经存在基类的现有上下文管理器可以通过 使用^ TT1}$作为混合类:

from contextdecorator import ContextDecorator

class mycontext(ContextBaseClass, ContextDecorator):
   def __enter__(self):
      return self

   def __exit__(self, *exc):
      return False

contextdecorator还包含contextlib.contextmanager的实现 使用ContextDecorator的。它创建的上下文管理器可以用作 以及with语句。

from contextdecorator import contextmanager

@contextmanager
def mycontext(*args):
   print 'Started'
   try:
      yield
   finally:
      print 'Finished!'

>>> @mycontext('some', 'args')
... def function():
...    print 'In the middle'
...
Started
In the middle
Finished!

>>> with mycontext('some', 'args'):
...    print 'In the middle'
...
Started
In the middle
Finished!

存储库和问题跟踪程序:

该项目可从PyPI下载 因此可以轻松安装:

^{tt6}$
^{tt7}$

测试需要unittest2 去跑步。

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
安卓 studio安装的java Unity本机广告   java如何将映射转换为对象   java我试图使用rest控制器从h2数据库中检索记录,但它说没有数据集   反思为什么会抛出java。lang.InstanceException?   在opensuse中找不到Java/javac   java为Android上的谷歌地图添加了5900多个标记。如何有效地做   java如何在if语句中使用循环   java如何在JPA(Hibernate)中映射一对多关系和复合主键?   如何在Java中读取和写入外部进程?   Java线程。睡眠时间最短   java使用EclipseGradle插件如何离线托管和使用依赖项(库jar文件)   java为什么虚拟引用在排队时没有被清除?   java无法理解如何创建用于响铃报警的取消按钮   java解析不应通过注入容器错误发生   java Toast或ProgressDialog不显示   java在自定义对象上使用优先级队列的更好方法   java格式的。wmv文件。(或者任何视频文件都很好)   从页面调用另一个侦听器后,不会调用java JSF<f:ajax>侦听器   java注释ConfigApplicationContext不能多次刷新有什么原因吗?