Julian Bilcke
Julian Bilcke

Reputation: 309

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

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)

Upvotes: 12

Views: 10792

Answers (2)

fijal
fijal

Reputation: 3190

Note that this code works just fine on PyPy (where there is no really distinction between those two function types).

(pypy)fijal@helmut:~$ python
class C(Python 2.7.1 (f1e873c5533d, Sep 19 2011, 02:01:57)
[PyPy 1.6.0-dev1 with GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Welcome to rlcompleter2 0.96
for nice experiences hit <tab> multiple times
And now for something completely different: ``PyPy needs a Just-in-Time JIT''
>>>> class C:
....  def __init__(self, a, b=4):
....    pass
.... 
>>>> import inspect
>>>> inspect.getargspec(C.__init__)
ArgSpec(args=['self', 'a', 'b'], varargs=None, keywords=None, defaults=(4,))
>>>> 

Upvotes: 8

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798626

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.

Upvotes: 9

Related Questions