在Python中充当装饰器和上下文管理器的函数吗?
这可能会使事情有点过头,但主要出于好奇。
This might be pushing things a little too far, but mostly out of curiosity..
是否有可能有一个可调用的对象(函数/类) 同时充当上下文管理器和装饰器:
Would it be possible to have a callable object (function/class) that acts as both a Context Manager and a decorator at the same time:
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')
从Python 3.2开始,标准库甚至都包含对此的支持。从类 contextlib.ContextDecorator $ c派生$ c>
使编写可用作装饰器或上下文管理器的类变得容易。此功能可以很容易地反向移植到Python 2.x-这是一个基本的实现:
Starting in Python 3.2, support for this is even included in the standard library. Deriving from the class contextlib.ContextDecorator
makes it easy to write classes that can be used as both, a decorator or a context manager. This functionality could be easily backported to Python 2.x -- here is a basic implementation:
class ContextDecorator(object):
def __call__(self, f):
@functools.wraps(f)
def decorated(*args, **kwds):
with self:
return f(*args, **kwds)
return decorated
从此类中派生上下文管理器并照常定义 __ enter __()
和 __ exit __()
方法。
Derive your context manager from this class and define the __enter__()
and __exit__()
methods as usual.