简体   繁体   中英

Python: Passing the default values of function' arguments to *args or **kwargs

Consider example:

def decorator(func):
    def wrapper(*args, **kwargs):
        print(args, kwargs)
        func(*args, **kwargs)
    return wrapper

@decorator
def foo(x, y, z=0):
    pass

foo(5, 5)

Output:

(5, 5) {}

Why not (5, 5) {'z': 0} ? How to pass all default values of the function foo to *args or **kwargs using only decorator (for functions) or metaclass (for class methods, eg __init__ )?

The wrapper is just a normal function. It does not have "access" to the internals of the wrapped function.

You would have to use introspection to get them. See a related question:

How to find out the default values of a particular function's argument in another function in Python?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM