Jinendra Khabiya
Jinendra Khabiya

Reputation: 85

How to print __init__ function arguments in python?

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

Upvotes: 8

Views: 14631

Answers (2)

RunOrVeith
RunOrVeith

Reputation: 4805

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])

Upvotes: 11

DSH
DSH

Reputation: 1139

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.

Upvotes: 3

Related Questions