Reputation: 807
I want to create a decorator which can wrap around functions with different numbers of variables. For example, below I have two functions abc
and abcd
, taking 2 and 3 arguments respectively. I want the wrapper to take a variable number of arguments in order to deal with this. However, when I run the code, I get TypeError: _wrapper() takes exactly 0 arguments (2 given)
, as though the **kwargs
was ignored.
Why is this, and how do I fix this?
def dec(function):
def _wrapper(**kwargs):
print len(kwargs)
function(**kwargs)
return _wrapper
@dec
def abc(a, b):
return a*b
@dec
def abcd(a, b, c):
return a*b*c
Upvotes: 4
Views: 3941
Reputation: 4476
Python has two variable argument variables: *args
and **kwargs
. args
is a list of arguments specified without names (e.g. func(1,2,3)
), while kwargs
is a dictionary of arguments with names (e.g. func(x=1, y=2, z=3)
).
Your code is only accepting the kwargs, so you also need to add the unnamed args:
def dec(function):
def _wrapper(*args, **kwargs):
print len(args) + len(kwargs)
return function(*args, **kwargs)
return _wrapper
Upvotes: 7