Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

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

I have a function whose name is ‘aMethod2’ in a script qux.py whose contents are not known to me.

How do I find the number of arguments of this function using given script?


1 Answer
Rajendra Dharmkar

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
Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.