Computer >> Computer tutorials >  >> Programming >> Python

How can I find the number of arguments of a Python function?


Suppose there is a script qux.py as follows

#qux.py
def aMethod1(arg1, arg2):
     pass
def aMethod2(arg1,arg2, arg3, arg4, arg5):
    pass

Assuming you don’t have access to contents of this script, you can find the number of arguments in the given function as follows

To find a list of parameter names inside a python function we import the inspect module and also import the given script qux.py

We get a list of all arguments of a function foo() by using inspect.getargspec(foo). The first of this list is again a list of normal arguments. If x = inspect.getargspec(foo), the number of arguments is found by len(x[0]). 

#fubar.py
import qux
import inspect
x=inspect.getargspec(qux.aMethod1)
y=inspect.getargspec(qux.aMethod2)
print(llen(y[0]))

Running this script at the terminal

$ python fubar.py

We get the following output

5