Given that a function a_method
has been defined like
def a_method(arg1, arg2): pass
Starting from a_method
itself, how can I get the argument names – for example, as a tuple of strings, like ("arg1", "arg2")
?
Advertisement
Answer
Take a look at the inspect
module – this will do the inspection of the various code object properties for you.
>>> inspect.getfullargspec(a_method) (['arg1', 'arg2'], None, None, None)
The other results are the name of the *args and **kwargs variables, and the defaults provided. ie.
>>> def foo(a, b, c=4, *arglist, **keywords): pass >>> inspect.getfullargspec(foo) (['a', 'b', 'c'], 'arglist', 'keywords', (4,))
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 get a ValueError
if you use inspect.getfullargspec()
on a built-in function.
Since Python 3.3, you can use inspect.signature()
to see the call signature of a callable object:
>>> inspect.signature(foo) <Signature (a, b, c=4, *arglist, **keywords)>