Is there a way to get the parameter names a function takes?
def foo(bar, buz): pass magical_way(foo) == ["bar", "buz"]
It means that parameter(s) that comes after * are keyword only parameters.
To extract the number and names of the arguments from a function or function[something] to return ("arg1", "arg2"), we use the inspect module. The given code is written as follows using inspect module to find the parameters inside the functions aMethod and foo.
Python has *args which allow us to pass the variable number of non keyword arguments to function. In the function, we should use an asterisk * before the parameter name to pass variable length arguments.
You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.
Use the inspect module from Python's standard library (the cleanest, most solid way to perform introspection).
Specifically, inspect.getargspec(f)
returns the names and default values of f
's arguments -- if you only want the names and don't care about special forms *a
, **k
,
import inspect def magical_way(f): return inspect.getargspec(f)[0]
completely meets your expressed requirements.
>>> import inspect >>> def foo(bar, buz): ... pass ... >>> inspect.getargspec(foo) ArgSpec(args=['bar', 'buz'], varargs=None, keywords=None, defaults=None) >>> def magical_way(func): ... return inspect.getargspec(func).args ... >>> magical_way(foo) ['bar', 'buz']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With