7

I am trying to create a dictionary of class names residing in module to their constructor args.

Constructor args should also be a dictionary where I will store the default values of the arguments wherever defined.

Any leads will be really helpful. Thanks in advance.

To provide more details about the use case, What I am trying to do here is for all the classes mentioned in the image image

I want to get the constructor parameters for e.g. please refer below image image

Jinendra Khabiya
  • 75
  • 1
  • 1
  • 7
  • 1
    Does this answer your question? [Introspecting arguments from the constructor function \_\_init\_\_ in Python](https://stackoverflow.com/questions/36849837/introspecting-arguments-from-the-constructor-function-init-in-python) – ffi Jul 23 '21 at 08:42

2 Answers2

11

If I understand you correctly, you just want the name of the parameters in the signature of your __init__.

That is actually quite simple using the inspect module:

Modern python answer:

import inspect

signature = inspect.signature(your_class.__init__).parameters
for name, parameter in signature.items():
    print(name, parameter.default, parameter.annotation, parameter.kind)

Outdated answer

import inspect

signature = inspect.getargspec(your_class.__init__)
signature.args # All arguments explicitly named in the __init__ function 
signature.defaults # Tuple containing all default arguments
signature.varargs # Name of the parameter that can take *args (or None)
signature.keywords # Name of the parameter that can take **kwargs (or None)

You can map the default arguments to the corresponding argument names like this:

argument_defaults = zip(signature.args[::-1], signature.defaults[::-1])
Nicoolasens
  • 2,871
  • 17
  • 22
RunOrVeith
  • 4,487
  • 4
  • 32
  • 50
  • 1
    Note that `getargspec` has been deprecated since 3.0. For 2/3 compat code `getfullargspec` should be used, and [`signature()`](https://docs.python.org/3/library/inspect.html#inspect.signature) if going for modern python only. – Ilja Everilä Apr 08 '17 at 11:20
  • Thanks for the answer. Though When I try to this code this gives me something like: ['self'] None args kwargs. But it does not print the actual arguments. I may be missing out something here. I updated the question with more details to explain the actual use case. – Jinendra Khabiya Apr 08 '17 at 11:33
  • `self`is always the first parameter to the `__init__` call. You can just filter it out. Otherwise I do not understand your question. – RunOrVeith Apr 08 '17 at 11:46
  • 1
    You can do `inspect.signature(your_class)`, without the `__init__`, in this case it doesn't list `self`. – Mathieu Longtin May 27 '20 at 03:24
3

Most recently, the following works:

import inspect

signature = inspect.signature(yourclass.__init__)

for param in signature.parameters.values():
    print(param)

The difference being (compared to the accepted answer), that the parameters instance variable needs to be accessed.

DSH
  • 1,038
  • 16
  • 27