Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python inspect.getargspec with built-in function

I'm trying to figure out the arguments of a method retrieved from a module. I found an inspect module with a handy function, getargspec. It works for a function that I define, but won't work for functions from an imported module.

import math, inspect
def foobar(a,b=11): pass
inspect.getargspec(foobar)  # this works
inspect.getargspec(math.sin) # this doesn't

I'll get an error like this:

   File "C:\...\Python 2.5\Lib\inspect.py", line 743, in getargspec
     raise TypeError('arg is not a Python function')
 TypeError: arg is not a Python function

Is inspect.getargspec designed only for local functions or am I doing something wrong?

like image 960
PeetWc Avatar asked Jul 05 '12 11:07

PeetWc


People also ask

How do you inspect a module in Python?

Methods to verify the type of token: isclass(): The isclass() method returns True if that object is a class or false otherwise. When it is combined with the getmembers() functions it shows the class and its type. It is used to inspect live classes.

How do you show function arguments in python?

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.

What is inspect stack ()?

inspect. stack() returns a list with frame records. In function whoami() : inspect. stack()[1] is the frame record of the function that calls whoami , like foo() and bar() . The fourth element of the frame record ( inspect.


2 Answers

It is impossible to get this kind of information for a function that is implemented in C instead of Python.

The reason for this is that there is no way to find out what arguments the method accepts except by parsing the (free-form) docstring since arguments are passed in a (somewhat) getarg-like way - i.e. it's impossible to find out what arguments it accepts without actually executing the function.

like image 113
ThiefMaster Avatar answered Oct 24 '22 21:10

ThiefMaster


You can get the doc string for such functions/methods which nearly always contains the same type of information as getargspec. (I.e. param names, no. of params, optional ones, default values).

In your example

import math
math.sin.__doc__

Gives

"sin(x)

Return the sine of x (measured in radians)"

Unfortunately there are several different standards in operation. See What is the standard Python docstring format?

You could detect which of the standards is in use, and then grab the info that way. From the above link it looks like pyment could be helpful in doing just that.

like image 32
Andrew Norris Avatar answered Oct 24 '22 20:10

Andrew Norris