I am trying to find a way to pass my function's default arguments to the decorator. I have to say I am fairly new to the decorator business, so maybe I just don't understand it properly, but I have not found any answers yet.
So here's my modified example from the Python functools.wraps
manual page.
from functools import wraps
def my_decorator(f):
@wraps(f)
def wrapper(*args, **kwds):
print('Calling decorated function')
print('args:', args)
print('kwargs:', kwds)
return f(*args, **kwds)
return wrapper
@my_decorator
def example(i, j=0):
"""Docstring"""
print('Called example function')
example(i=1)
I want the j=0
to be passed, too. So the output should be:
Calling decorated function
args: ()
kwargs: {'i': 1, 'j': 0}
Called example function
But instead I get
Calling decorated function
args: ()
kwargs: {'i': 1}
Called example function
j=0
is passed, but not insidewrapper
. If youprint i, j
insideexample
, you'll see that it is there. You could use e.g.inspect.getargspec(f)
to see what defaults are set on the function being decorated, but why do you need to access the default inwrapper
? – Bairdexample
, but I needj
to be passed to thewrapper
because it is needed for calculations i am doing with with many several functions. But generally usinginspect.getargspec(f)
would work, thank you. – Isador