如何在不使用 @ 语法的情况下使用 "double layered" 装饰器?

How to use a "double layered" decorator without using the @ syntax?

假设我有这个装饰器:

def decorator_with_args(decorator_arg1, decorator_arg2):                
    def decorator(func):
        def wrapped(*args, **kwargs):
            if decorator_arg1 == 'arg1' and decorator_arg2 == 'arg2':
                return func(*args, **kwargs)
        return wrapped
    return decorator

通常你会像这样装饰一个函数:

@decorator_with_args('arg1', 'arg2')
def function():
    return 'foo'

>>> foo = function()
'foo'

如何在不使用 @ 语法的情况下调用它?

我知道如果它只是一个单层装饰器(即没有 args 的装饰器),你会这样称呼它,就像这样将它包装在装饰器函数中:

>>> foo = decorator(function)
'foo'

请注意 function 未被调用。如果装饰器和函数都有需要传递的参数,这将如何工作?

>>> foo = decorator_with_args(decorator(wrapped_function))

但是装饰器和原始函数的*args**kwargs去哪儿了呢?

decorator_with_args() 是一个装饰器工厂——也就是说,一个 returns 装饰器的函数。这意味着为了在没有 @ 语法的情况下使用它,你需要用它的参数调用它,然后用你的函数作为参数调用结果。

外观如下:

def function():
    return 'foo'

function = decorator_with_args('arg1', 'arg2')(function)

>>> function()
'foo'

请注意,这类似于使用带有或不带有 @ 语法的常规装饰器之间的区别:

@deco
def func(arg):
    # ...

def func(arg):
    # ...

func = deco(func)

作为

@deco_fac(x, y)
def func(arg):
    # ...

def func(arg):
    # ...

func = deco_fac(x, y)(func)