8

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

1

2 Answers 2

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])
Sign up to request clarification or add additional context in comments.

4 Comments

Note that getargspec has been deprecated since 3.0. For 2/3 compat code getfullargspec should be used, and signature() if going for modern python only.
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.
selfis always the first parameter to the __init__ call. You can just filter it out. Otherwise I do not understand your question.
You can do inspect.signature(your_class), without the __init__, in this case it doesn't list self.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.