在Python中充当装饰器和上下文管理器的函数吗?
这可能会使事情有点过头,但主要出于好奇。
是否有可能 同时 充当上下文管理器和装饰器的可调用对象(函数/类):
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
使编写既可以用作装饰器又可以用作上下文管理器的类变得容易。此功能可以很容易地反向移植到Python
2.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__()
照常定义和方法。