创建充当装饰器和上下文管理器的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 去跑步。