如何用参数切换装饰器?

时间:2019-06-09 22:37:22

标签: python toggle decorator python-decorators

我需要一个装饰器,它可以收集给定功能的使用情况统计信息,但也可以在代码中动态切换。我在SO上找到了一个示例-toggling decorators

import functools

class SwitchedDecorator:
    def __init__(self, enabled_func):
        self._enabled = False
        self._enabled_func = enabled_func

    @property
    def enabled(self):
        return self._enabled

    @enabled.setter
    def enabled(self, new_value):
        if not isinstance(new_value, bool):
            raise ValueError("enabled can only be set to a boolean value")
        self._enabled = new_value

    def __call__(self, target):
        if self._enabled:
            return self._enabled_func(target)
        return target


def deco_func(target):
    """This is the actual decorator function.  It's written just like any other decorator."""
    def g(*args,**kwargs):
        print("your function has been wrapped")
        return target(*args,**kwargs)
    functools.update_wrapper(g, target)
    return g


# This is where we wrap our decorator in the SwitchedDecorator class.
my_decorator = SwitchedDecorator(deco_func)

# Now my_decorator functions just like the deco_func decorator,
# EXCEPT that we can turn it on and off.
my_decorator.enabled=True

@my_decorator
def example1():
    print("example1 function")

# we'll now disable my_decorator.  Any subsequent uses will not
# actually decorate the target function.
my_decorator.enabled=False
@my_decorator
def example2():
    print("example2 function")

这适用于不带任何参数的装饰器,但是我需要一个也带参数的装饰器。我查找了创建示例的示例,但未能提出适合该模型的解决方案。主要是,具有此示例提供的enable属性,但也可以传递参数。我创建了一个deco_func(),可以有参数

def decoratorFunctionWithArguments(arg1, arg2):
    def wrap(f):
        print "Inside wrap()"
        def wrapped_f(*args):
            print "Inside wrapped_f()"
            print "Decorator arguments:", arg1, arg2
            f(*args)
            print "After f(*args)"
        return wrapped_f

    return wrap

但是我无法将其传递给SwitchedDecorator,因为它抱怨__call__函数中的参数。

0 个答案:

没有答案