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")?
Returns a list of argument names, takes care of partials and regular functions:
In CPython, the number of arguments is
and their names are in the beginning of
These are implementation details of CPython, so this probably does not work in other implementations of Python, such as IronPython and Jython.
One portable way to admit "pass-through" arguments is to define your function with the signature
func(*args, **kwargs)
. This is used a lot in e.g. matplotlib, where the outer API layer passes lots of keyword arguments to the lower-level API.Python 3.5+:
So previously:
Now:
To test:
Given that we have function 'function' which takes argument 'arg', this will evaluate as True, otherwise as False.
Example from the Python console:
What about
dir()
andvars()
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.
I think what you're looking for is the locals method -
The Python 3 version is:
The method returns a dictionary containing both args and kwargs.