簡體   English   中英

用 python 中的參數組合裝飾器

[英]Composing decorator with parameters in python

我想使用一個裝飾器( composer )作為參數n個裝飾器,這個裝飾器將用於裝飾function。 另外我想從兩個來源傳遞一些參數,一個在作曲家中名為“SKIP”的參數,另一個由parameter_sender裝飾器發送的名為“parameter”的參數。 這是我嘗試過的:

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

這是我想在哪里使用它的示例。 在這個例子中,如果變量 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)

但我有一個錯誤說:

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

即使 if 語句正在工作。 PD:它可以在沒有composer中指示的行的情況下工作。

下面的代碼應該做的事情。 您試圖為外部 scope 的變量設置值。 在我的示例中,我使用了單獨的臨時變量組合。

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