创建可以作为装饰器或上下文管理器使用的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还包含一个使用ContextDecorator的contextlib.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 查看哈希值)
关闭
contextdecorator-0.10.0.zip的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | e6ee12393ea89a6222152cd103d8f55397ff13e08cb513f48ccc2739768b9171 |
|
MD5 | 2ef3ed0500116cc2ee42714b38e2c893 |
|
BLAKE2b-256 | f68bbb30402c613cb77ab5822ed71ac00f4349231519161ed0265bfb5f5aaae4 |
关闭
contextdecorator-0.10.0.tar.gz的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | 44645affa722c72b4931d48a4ff9265a8df19373e20e12334bca4ec2104f8619 |
|
MD5 | 779973c0e9502c9fdc7add9628cbb58d |
|
BLAKE2b-256 | 774303f264fa07fb0f794bfe174751eb6e6e294a89fc53af87ea1cb0df26ac18 |