跳转到主要内容

创建可以作为装饰器或上下文管理器使用的API。

项目描述

如果您是库或框架的创建者,那么能够创建既可以用作装饰器也可以用作上下文管理器的API会很好。

contextdecorator模块是Python 3.2中添加到contextlib模块的新功能的回溯。contextdecorator与Python 2.4+兼容,包括Python 3。

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

可以使用ContextDecorator作为混合类来扩展已具有基类的现有上下文管理器

from contextdecorator import ContextDecorator

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

   def __exit__(self, *exc):
      return False

contextdecorator还包含一个使用ContextDecoratorcontextlib.contextmanager实现。它创建的上下文管理器可以用作装饰器,也可以用在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下载,因此可以轻松安装

pip install -U contextdecorator
使用easy_install -U 安装contextdecorator

测试需要运行unittest2

项目详情


下载文件

下载适合您平台的文件。如果您不确定选择哪个,请了解更多关于安装包的信息。

源分布

contextdecorator-0.10.0.zip (6.8 kB 查看哈希值)

上传时间

contextdecorator-0.10.0.tar.gz (4.6 kB 查看哈希值)

上传时间

由以下支持