How to get arguments list of a built-in Python class constructor?

Julian Bilcke picture Julian Bilcke · Oct 2, 2011 · Viewed 9k times · Source

I'm trying to use the inspect module, however it seems I can't use it on a built-in (native?) class, or else I misunderstood.

I'm using Python 2.7 and tried with Python 3.2.

This is working:

>>> import inspect
>>> class C:
...     def __init__(self,a,b=4):
...         self.sum = a + b
... 
>>> inspect.getargspec(C.__init__)
ArgSpec(args=['self','a', 'b'], varargs=None, keywords=None, defaults=(4,))

This is not working:

>>> import inspect
>>> import ast
>>> inspect.getargspec(ast.If.__init__)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/inspect.py", line 813, in getargspec
    raise TypeError('{!r} is not a Python function'.format(func))
TypeError: <slot wrapper '__init__' of '_ast.AST' objects> is not a Python function

I am wondering if there is another technique to get these parameters automatically?

(In my case, I think about an alternative which would be to parse the Python grammar, the ASDL file which explain how to init AST nodes using some code I saw in PyPy Project's source, but I'm wondering if there is another way)

Answer

Ignacio Vazquez-Abrams picture Ignacio Vazquez-Abrams · Oct 2, 2011

There is no way to get them, as they are a property of the C code behind the function, and not of the function itself.