不带括号调用装饰器(不改变装饰器定义)

Calling Decorator without Parentheses (without changing decorator definition)

假设我有以下装饰器。 (重复一个功能n次)

def repeat(num_times=4):
    def decorator_repeat(func):
        @functools.wraps(func)
        def wrapper_repeat(*args, **kwargs):
            for _ in range(num_times):
                value = func(*args, **kwargs)
            return value
        return wrapper_repeat
    return decorator_repeat

现在,它确实有一个默认值4,但是,即使我想用默认值调用它,我仍然必须这样调用它

@repeat()
def my_function():
    print("hello")

而不是

@repeat
def my_function():
    print("hello")

现在,我可以将装饰器的定义更改为

def repeat(_func=None, *, num_times=2):
    def decorator_repeat(func):
        @functools.wraps(func)
        def wrapper_repeat(*args, **kwargs):
            for _ in range(num_times):
                value = func(*args, **kwargs)
            return value
        return wrapper_repeat

    if _func is None:
        return decorator_repeat
    else:
        return decorator_repeat(_func)

如果我愿意,可以启用不带参数调用它的功能。

但是,不改装饰器的代码,而是再定义一个装饰器,是否可以实现呢?

即我想定义一个装饰器 enable_direct 这样我就可以将 @enable_direct 添加到我的装饰器定义中并具有相同的效果。 (即如下)

@enable_direct
def repeat(num_times=4):
    def decorator_repeat(func):
        @functools.wraps(func)
        def wrapper_repeat(*args, **kwargs):
            for _ in range(num_times):
                value = func(*args, **kwargs)
            return value
        return wrapper_repeat
    return decorator_repeat

注:

我知道 How to create a Python decorator that can be used either with or without parameters?

中提到的解决方案

该问题中的定义具有不同的签名,如果重新开始,可以遵循该模式。但是,假设我有 20-30 个这样的装饰器定义(3 层嵌套)。我希望所有这些都能够在没有括号的情况下被调用。 def repeat 语句没有函数参数。该问题中的函数有 2 层嵌套,而我的有 3 层。我想问一下是否可以在不更改函数定义的情况下使用此类装饰器定义(意味着用括号调用)。那里接受的答案有不同的签名,因此在这个问题上没有实质要求。

注 2: 在尝试那里给出的双环绕定义之前,我没有问这个问题。不带括号调用它 returns 另一个函数(如果函数的签名与描述的一样)。

你在这里:

import functools


def enable_direct(decorator):
    @functools.wraps(decorator)
    def wrapper(*args, **kwargs):
        f = args[0]
        if callable(f):
            return decorator()(f)  # pass the function to be decorated
        else:
            return decorator(*args, **kwargs)  # pass the specified params
    return wrapper


@enable_direct
def repeat(num_times=4):
    def decorator_repeat(func):
        @functools.wraps(func)
        def wrapper_repeat(*args, **kwargs):
            for _ in range(num_times):
                value = func(*args, **kwargs)
            return value
        return wrapper_repeat
    return decorator_repeat


@repeat
def my_func(name):
    print(name)

@repeat(2)
def my_func2(name):
    print(name)


print(my_func)
print(my_func2)

my_func("Gino")
my_func2("Mario")

产生

<function my_func at 0x7f629f091b70>
<function my_func2 at 0x7f629f091bf8>
Gino
Gino
Gino
Gino
Mario
Mario