I am trying to access all the arguments passed to a function in a decorator, including optional arguments. Consider this example:
def decorator(fn):
def wrapper(*args, **kwargs):
print 'in wrapper', args, kwargs
fn(*args, **kwargs)
return wrapper
@decorator
def myFn(arg1, arg2, arg3=None):
print 'in myFn', arg1, arg2, arg3
myFn(1,2)
myFn(1,2,3)
If I run this, I will get:
in wrapper (1, 2) {}
in myFn 1 2 None
in wrapper (1, 2, 3) {}
in myFn 1 2 3
In the first run, since I do not specify 3 arguments, arg3 is defined as None for the purposes of myFn. But the fact that it is arg3 == Nonenot available inside the decorator is either in args or in kwargs. If I explicitly pass it to myFn, it will appear inside the decorator, but if I use the default, it will not be found anywhere.
Why is this? And how can this be fixed?
source
share