2024-09-26 17:42:43 发布
网友
这可能有点过分了,但主要是出于好奇。。
是否有可能同时充当上下文管理器和装饰器的可调用对象(函数/类):
def xxx(*args, **kw): # or as a class @xxx(foo, bar) def im_decorated(a, b): print('do the stuff') with xxx(foo, bar): print('do the stuff')
在Python3.2+中,您可以使用^{}定义一个上下文管理器,它也是一个装饰器。
从文档中:
contextmanager() uses ContextDecorator so the context managers it creates can be used as decorators as well as in with statements
contextmanager()
ContextDecorator
with
示例用法:
>>> from contextlib import contextmanager >>> @contextmanager ... def example_manager(message): ... print('Starting', message) ... try: ... yield ... finally: ... print('Done', message) ... >>> with example_manager('printing Hello World'): ... print('Hello, World!') ... Starting printing Hello World Hello, World! Done printing Hello World >>> >>> @example_manager('running my function') ... def some_function(): ... print('Inside my function') ... >>> some_function() Starting running my function Inside my function Done running my function
class Decontext(object): """ makes a context manager also act as decorator """ def __init__(self, context_manager): self._cm = context_manager def __enter__(self): return self._cm.__enter__() def __exit__(self, *args, **kwds): return self._cm.__exit__(*args, **kwds) def __call__(self, func): def wrapper(*args, **kwds): with self: return func(*args, **kwds) return wrapper
现在你可以:
mydeco = Decontext(some_context_manager)
这使得
@mydeco def foo(...): do_bar() foo(...)
以及
with mydeco: do_bar()
从Python3.2开始,标准库中甚至包含了对它的支持。从类^{}派生可以很容易地编写可以同时用作装饰器和上下文管理器的类。这个功能可以很容易地移植到Python2.x——下面是一个基本的实现:
class ContextDecorator(object): def __call__(self, f): @functools.wraps(f) def decorated(*args, **kwds): with self: return f(*args, **kwds) return decorated
从这个类派生上下文管理器,并像往常一样定义__enter__()和__exit__()方法。
__enter__()
__exit__()
在Python3.2+中,您可以使用^{} 定义一个上下文管理器,它也是一个装饰器。
从文档中:
示例用法:
现在你可以:
这使得
以及
从Python3.2开始,标准库中甚至包含了对它的支持。从类^{} 派生可以很容易地编写可以同时用作装饰器和上下文管理器的类。这个功能可以很容易地移植到Python2.x——下面是一个基本的实现:
从这个类派生上下文管理器,并像往常一样定义
__enter__()
和__exit__()
方法。相关问题 更多 >
编程相关推荐