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, below is to make *args
and **kwargs
into a dict
(use OrderedDict
for python < 3.6 to maintain dict
orders):
from functools import wraps
def display_param(func):
@wraps(func)
def wrapper(*args, **kwargs):
param = inspect.signature(func).parameters
all_param = {
k: args[n] if n < len(args) else v.default
for n, (k, v) in enumerate(param.items()) if k != 'kwargs'
}
all_param .update(kwargs)
print(all_param)
return func(**all_param)
return wrapper
To update a little bit Brian's answer, there is now a nice backport of inspect.signature
that you can use in older python versions: funcsigs.
So my personal preference would go for
try: # python 3.3+
from inspect import signature
except ImportError:
from funcsigs import signature
def aMethod(arg1, arg2):
pass
sig = signature(aMethod)
print(sig)
For fun, if you're interested in playing with Signature
objects and even creating functions with random signatures dynamically you can have a look at my makefun project.
What about dir()
and vars()
now?
Seems doing exactly what is being asked super simply…
Must be called from within the function scope.
But be wary that it will return all local variables so be sure to do it at the very beginning of the function if needed.
Also note that, as pointed out in the comments, this doesn't allow it to be done from outside the scope. So not exactly OP's scenario but still matches the question title. Hence my answer.