Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print __init__ function arguments in python?

Tags:

python-3.x

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

like image 203
Jinendra Khabiya Avatar asked Apr 08 '17 11:04

Jinendra Khabiya


1 Answers

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__)
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])
like image 87
RunOrVeith Avatar answered Oct 09 '22 21:10

RunOrVeith