[英]How can I send unknown list of arguments to a python decorator?
I have created a python decorator as shown below. 我创建了一个python装饰器,如下所示。 I want this decorator to accept an unknown list of arguments. 我希望这个装饰器接受一个未知的参数列表。 But the code below doesn't work. 但是下面的代码不起作用。
#!/usr/bin/env python
from functools import wraps
def my_decorator(decorated_function, **kwargs):
print "kwargs = {}".format(kwargs)
@wraps(decorated_function)
def inner_function(*args, **kwargs):
print "Hello world"
return decorated_function(*args, **kwargs)
return inner_function
@my_decorator(arg_1="Yolo", arg2="Bolo")
def my_func():
print "Woo Hoo!"
my_func()
When I run it, I get this error: 当我运行它时,我收到此错误:
File "./decorator_test.py", line 14, in <module>
@my_decorator(arg_1="Yolo", arg2="Bolo")
TypeError: my_decorator() takes exactly 1 argument (0 given)
Why is the **kwargs
not accepting the multiple arguments I'm sending into the decorator? 为什么**kwargs
不接受我发送到装饰器的多个参数? How can I fix it? 我该如何解决?
Essentially, when you have a decorator that accepts arguments, you're kind of calling it twice, once with the keyword arguments, and then again with just the function to be decorated. 基本上,当你有一个接受参数的装饰器时,你有两次调用它,一次用关键字参数调用,然后再调用一个要装饰的函数。
Before the @deco
syntax, you would decorate a function just by passing it into the decorator function 在@deco
语法之前, @deco
将函数传递给装饰器函数即可修饰函数
func = deco(func)
And if you wanted to include other keyword arguments, you could just pass them in at the same time 如果你想包含其他关键字参数,你可以同时传递它们
func = deco(func, arg=True, arg2=5)
But the @deco
syntax doesn't allow that, it works more like this, so you're calling a function returned by the decorator function. 但是@deco
语法不允许这样,它更像是这样,所以你正在调用装饰器函数返回的函数。
func = deco(arg=True, arg2=5)(func)
To do this with the @deco
syntax, you would create a decorator that tests to see whether it was called with just a function (the decoration part), or whether it was called with keyword arguments (which sets up the decorator to be passed a function). 要使用@deco
语法执行此@deco
,您将创建一个装饰器,用于测试是否仅使用函数(装饰部分)调用它,或者是否使用关键字参数调用它(设置要传递的装饰器)功能)。
def deco_with_kwargs(func=None, **kwargs):
def deco(func_):
def wrapped_func(*fargs, **fkwargs):
print kwargs
return func_(*fargs, **fkwargs)
return wrapped_func
if func:
return deco(func)
else:
return deco
You could use it like this without any keyword arguments. 您可以在没有任何关键字参数的情况下使用它。
@deco_with_args
def my_func():
return 1
Or you could call it like this with keyword arguments. 或者您可以使用关键字参数调用它。 In this case, you're actually calling the decorator function, which returns another decorator function, which is then called to actually decorate the function. 在这种情况下,您实际上正在调用装饰器函数,该函数返回另一个装饰器函数,然后调用该函数来实际装饰该函数。
@deco_with_args(test=True)
def my_func():
return 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.