创建充当装饰器和上下文管理器的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第三方库


热门话题
从对象进行java类型转换   javascript如何处理JS从复选框中获取的值,然后在Java操作中使用它?   使用Mongo Java驱动程序3.0从Mongo集合获取字段的不同值时出现mongodb异常   当AEM工作流失败时,java是否发送电子邮件通知?   java在同一路径上扩展REST类和重写方法   基于java的新闻网站管理系统   java如何在MySQL中防止时间戳舍入   java字节到整数   java JNI抛出中断方法执行吗?   比较JAVA中字符串内的数值   使用DropWizard对动态模式进行java JSON解析   json如何使用带点运算符的字符串访问嵌套java成员变量值   java在需要唯一元素和索引访问时设置vs列表   java以编程方式单击场景2D LibGDX中的按钮   java如何在Spring Boot中记录无效404请求的请求路径?   按钮按下时变量的随机Java抓取结果   更改屏幕后java应用程序崩溃   Java中使用通配符的泛型