67

这可能把事情推得太远了,但主要是出于好奇..

是否有可能同时充当上下文管理器和装饰器的可调用对象(函数/类):

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')
4

5 回答 5

60

从 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__()

于 2012-02-09T15:26:51.150 回答
42

在 Python 3.2+ 中,您可以使用@contextlib.contextmanager.

从文档:

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

于 2016-08-08T17:55:59.960 回答
15
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()
于 2012-02-09T15:38:10.320 回答
8

这是一个例子:

class ContextDecorator(object):
    def __init__(self, foo, bar):
        self.foo = foo
        self.bar = bar
        print("init", foo, bar)

    def __call__(self, f):
        print("call")
        def wrapped_f():
            print("about to call")
            f()
            print("done calling")
        return wrapped_f

    def __enter__(self):
        print("enter")

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("exit")

with ContextDecorator(1, 2):
    print("with")

@ContextDecorator(3, 4)
def sample():
    print("sample")

sample()

这打印:

init 1 2
enter
with
exit
init 3 4
call
about to call
sample
done calling
于 2012-02-09T15:35:03.737 回答
3

尽管我在这里同意(并赞成)@jterrace,但我添加了一个非常细微的变化,它返回装饰函数,并包括装饰器和装饰函数的参数。

class Decon:
    def __init__(self, a=None, b=None, c=True):
        self.a = a
        self.b = b
        self.c = c

    def __enter__(self):
        # only need to return self 
        # if you want access to it
        # inside the context
        return self 

    def __exit__(self, exit_type, exit_value, exit_traceback):
        # clean up anything you need to
        # otherwise, nothing much more here
        pass

    def __call__(self, func):
        def decorator(*args, **kwargs):
            with self:
                return func(*args, **kwargs)
        return decorator
于 2019-08-27T01:41:29.163 回答