How do I get the constructor signature for built-in types?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Jun 5 01:19:06 EDT 2012


The inspect.getargspec and getfullargspec functions allow you to extract 
the function call signature for Python functions and methods. This allows 
you to work out the constructor signature for pure-Python classes, by 
calling inspect.getargspec on the __init__ or __new__ method.


>>> import inspect
>>> class X:
...     def __init__(self, a, b, *args):
...             pass
... 
>>> inspect.getargspec(X.__init__)
ArgSpec(args=['self', 'a', 'b'], varargs='args', keywords=None, 
defaults=None)



So far so good. But if the __init__ method is inherited directly from a 
built-in, getargspec fails:


>>> class Y(int):
...     pass
... 
>>> inspect.getargspec(Y.__init__)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.2/inspect.py", line 794, in getargspec
    getfullargspec(func)
  File "/usr/local/lib/python3.2/inspect.py", line 821, in getfullargspec
    raise TypeError('{!r} is not a Python function'.format(func))
TypeError: <slot wrapper '__init__' of 'object' objects> is not a Python 
function


How do I programmatically get the argument spec of built-in types' 
__init__ or __new__ methods?



-- 
Steven



More information about the Python-list mailing list