简体   繁体   English

用 python 中的参数组合装饰器

[英]Composing decorator with parameters in python

I want to use a decorator ( composer ) that recevices as parameter n number of decorators, this decorators will be used to decorate a function.我想使用一个装饰器( composer )作为参数n个装饰器,这个装饰器将用于装饰function。 Also I want to pass some parameters from two origins, a parameter named "SKIP" in the composer and another parameter named "parameter" sent by the parameter_sender decorator.另外我想从两个来源传递一些参数,一个在作曲家中名为“SKIP”的参数,另一个由parameter_sender装饰器发送的名为“parameter”的参数。 Here's what I tried:这是我尝试过的:

def compose(*decorators, SKIP=None):
def something(func):
    @wraps(func)
    def func_wrap(parameter = None, **kwargs):
        try:
            if SKIP:
                print("I'm here")
                return func(parameter = parameter,**kwargs) 
            else:
                for decorator in reversed(decorators):
                    func = decorator(func, parameter = parameter,**kwargs) # --------- This line is providing the error ------------------
                return func
            raise exception
        except Exception as e:
            print(e)
            raise exception
    return func_wrap
return something

And here is an example of where do I want to use it.这是我想在哪里使用它的示例。 In this example I want to SKIP the composing of all the decorators if the variable SKIP is true.在这个例子中,如果变量 SKIP 为真,我想跳过所有装饰器的组合。

@application.route("/function/<id_something>", methods=['GET'])
@parameter_sender
@compose(decorator_1,decorator_2, SKIP=True)
def function (id_something, **kwargs):
    try:
        #TODO:
        return jsonify("ok")
    except Exception as e:
        print(e)

But i've got an error that says this:但我有一个错误说:

>>I'm here
>>local variable 'func' referenced before assignment

Even when the if statement is working.即使 if 语句正在工作。 PD: It works without the line indicated in the composer . PD:它可以在没有composer中指示的行的情况下工作。

The following code should do the thing.下面的代码应该做的事情。 You were trying to set a value for a variable from outer scope.您试图为外部 scope 的变量设置值。 In my example I used separate temp variable composition.在我的示例中,我使用了单独的临时变量组合。

def compose(*decorators, SKIP=None):
    def something(func):
        @wraps(func)
        def func_wrap(*args, **kwargs):
            try:
                if SKIP:
                    print("I'm here")
                    return func(*args, **kwargs)
                else:
                    composition = func
                    for decorator in reversed(decorators):
                        composition = decorator(composition)
                    return composition(*args, **kwargs)
            except Exception as e:
                print(e)
                raise
        return func_wrap
    return something

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

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