Home >Backend Development >Python Tutorial >How to Retrieve Method Parameter Names in Python?
Obtaining Method Parameter Names
Given a defined function like:
def a_method(arg1, arg2): pass
How can we retrieve the argument names as a tuple of strings, like ("arg1", "arg2")?
Using the Inspect Module
The inspect module enables us to inspect code objects and retrieve their properties. To obtain the argument names of a_method, use inspect.getfullargspec():
>>> inspect.getfullargspec(a_method) (['arg1', 'arg2'], None, None, None)
The result consists of the argument names and additional information, such as the names of the args and *kwargs variables and their default values.
def foo(a, b, c=4, *arglist, **keywords): pass >>> inspect.getfullargspec(foo) (['a', 'b', 'c'], 'arglist', 'keywords', (4,))
Using inspect.signature()
In Python 3.3 and later, we can use inspect.signature() to obtain the call signature of a callable object:
>>> inspect.signature(foo) <Signature (a, b, c=4, *arglist, **keywords)>
This provides a more detailed signature, including the parameter types and default values.
Note: Some callables in Python may not be introspectable, especially those defined in C in CPython. In such cases, inspect.getfullargspec() will raise a ValueError.
The above is the detailed content of How to Retrieve Method Parameter Names in Python?. For more information, please follow other related articles on the PHP Chinese website!