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

耗尽温柔 提交于 2020-01-11 09:32:42

问题


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, e.g. __init__)?


回答1:


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?



来源:https://stackoverflow.com/questions/27210551/python-passing-the-default-values-of-function-arguments-to-args-or-kwargs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!