Given the Python function:
def aMethod(arg1, arg2):
pass
How can I extract the number and names of the arguments. I.e., given that I have a reference to func, I want the func.[something] to return ("arg1", "arg2").
The usage scenario for this is that I have a decorator, and I wish to use the method arguments in the same order that they appear for the actual function as a key. I.e., how would the decorator look that printed "a,b" when I call aMethod("a", "b")?
Update for Brian's answer:
If a function in Python 3 has keyword-only arguments, then you need to use
inspect.getfullargspec
:yields this:
In python 3, below is to make
*args
and**kwargs
into adict
(useOrderedDict
for python < 3.6 to maintaindict
orders):Here is something I think will work for what you want, using a decorator.
Run it, it will yield the following output:
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'sbind()
method!For example, here is a decorator for printing a map like that:
Take a look at the inspect module - this will do the inspection of the various code object properties for you.
The other results are the name of the *args and **kwargs variables, and the defaults provided. ie.
Note that some callables may not be introspectable in certain implementations of Python. For Example, in CPython, some built-in functions defined in C provide no metadata about their arguments. As a result, you will obtain
ValueError
in the case you useinspect.getargspec()
with a built-in function.Since Python 3.3, you can use also the inspect.signature() in order to know the call signature of a callable object:
In a decorator method, you can list arguments of the original method in this way:
If the
**kwargs
are important for you, then it will be a bit complicated:Example: