Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 702
Julian Bilcke Avatar asked Oct 02 '11 17:10

Julian Bilcke


People also ask

What is __ init __ constructor in Python?

The __init__ method is the Python equivalent of the C++ constructor in an object-oriented approach. The __init__ function is called every time an object is created from a class. The __init__ method lets the class initialize the object's attributes and serves no other purpose. It is only used within classes.

How do you show function arguments in Python?

The inspect module helps in checking the objects present in the code that we have written. We are going to use two methods i.e. signature() and getargspec() methods from the inspect module to get the list of parameters name of function or method passed as an argument in one of the methods.


1 Answers

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,))
>>>> 
like image 71
fijal Avatar answered Sep 29 '22 17:09

fijal