在Python中充当装饰器和上下文管理器的函数?

2024-09-26 17:42:43 发布

您现在位置: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')

Tags: the对象函数管理器foodefbarargs
3条回答

在Python3.2+中,您可以使用^{}定义一个上下文管理器,它也是一个装饰器。

从文档中:

contextmanager() uses ContextDecorator so the context managers it creates can be used as decorators as well as in with statements

示例用法:

>>> 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__()方法。

相关问题 更多 >

    热门问题