Given the Python function:
def a_method(arg1, arg2):
pass
How can I extract the number and names of the arguments. I.e., given that I h
In Python 3.+ with the Signature
object at hand, an easy way to get a mapping between argument names to values, is using the Signature's bind()
method!
For example, here is a decorator for printing a map like that:
import inspect
def decorator(f):
def wrapper(*args, **kwargs):
bound_args = inspect.signature(f).bind(*args, **kwargs)
bound_args.apply_defaults()
print(dict(bound_args.arguments))
return f(*args, **kwargs)
return wrapper
@decorator
def foo(x, y, param_with_default="bars", **kwargs):
pass
foo(1, 2, extra="baz")
# This will print: {'kwargs': {'extra': 'baz'}, 'param_with_default': 'bars', 'y': 2, 'x': 1}