繁体   English   中英

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

[英]Function acting as both decorator and context manager in 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__()方法,像往常一样。

在Python 3.2+中,您可以使用@contextlib.contextmanager contextlib.contextmanager定义一个也是装饰器的上下文管理器。

来自文档:

contextmanager()使用ContextDecorator因此它创建的上下文管理器可以用作装饰器以及with语句

用法示例:

>>> 
>>> 
... 
... 
... 
... 
... 
... 
... 
>>> 
... 
... 
Starting printing Hello World
Hello, World!
Done printing Hello World
>>> 
>>> 
... 
... 
... 
>>> 
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()

这是一个例子:

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

虽然我同意(和赞成)@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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM