繁体   English   中英

如何检测装饰器中缺少的 arguments?

[英]How to detect missing arguments in decorator?

我想定义一个带有参数的装饰器,如果参数丢失,则会引发错误。

这是对简化示例的天真尝试:

def decorator_with_arg(a=None):

    if a is None :
        raise ValueError("Missing argument in decorator")

    def decorator(func):

        def wrapped_func(x):
            return func(x+ a)

        return wrapped_func

    return decorator

但是当我在没有参数的情况下使用这个装饰器时,它不会引发任何错误:

@decorator_with_arg
def simple_func(x):
    return 2*x

simple_func(1)

如何引发错误?

您没有正确使用您的装饰器,在您的代码中simple_func(1)只会返回wrapped_func ,因为@decorator_with_arg只会这样做:

simple_func = decorator_with_arg(simple_func)
#                                ^ this is passing a=simple_func
# now simple_func is the decorator function defined inside decorator_with_arg

您需要调用您的decorator_with_arg以使其返回decorator ,然后该装饰器将用于装饰 function:

@decorator_with_arg(100)
def simple_func(x):
    return 2*x

print(simple_func(1)) # 202

在任何情况下,如果你想强制一个参数,只需声明它而不使用默认值:

def decorator_with_arg(a):
    # ...

并删除if a is None检查。


如果您想避免在使用@decorator_with_arg而不是@decorator_with_arg()时出错,可以添加检查以确保a不是 function:

def decorator_with_arg(a):
    if callable(a):
        raise TypeError("Incorrect use of decorator")
    
    def decorator(func):
        def wrapped_func(x):
            return func(x + a)
        return wrapped_func
    return decorator


@decorator_with_arg
def func():
    return 1
# TypeError: Incorrect use of decorator


@decorator_with_arg(123)
def func():
    return 1
# All fine

暂无
暂无

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

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