Access to additional arguments in the decorator

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?

+3
source share
2 answers

This is quite normal and cannot be "fixed" ...

, : , , .

arg3=None - , . , ( ), .

:

def fn(arg1,arg2,arg3=None):
    pass

fn.func_defaults
-> (None,)

? ... , . , 100%:)

+6

decorator , :

from decorator import decorator

def decorate(f):
    def wrapper(f, *args, **kwargs):
        print 'in wrapper', args, kwargs
        return f(*args, **kwargs)
    return decorator(wrapper, f)

@decorate
def myFn(arg1, arg2, arg3=None):
    print 'in myFn', arg1, arg2, arg3

myFn(1, 2)
myFn(1, 2, 3)
myFn(1, 2, arg3=10)

:

in wrapper (1, 2, None) {}
in myFn 1 2 None
in wrapper (1, 2, 3) {}
in myFn 1 2 3
in wrapper (1, 2, 10) {}
in myFn 1 2 10
+3

All Articles