1

Pre-Info

We have a structure running on multiple machines which are communicating each other by using our json serializable objects to carry data between devices.

I am trying to create documentation for these classes by using markdown.

Problem


class BaseParams(JsonObject):
    """ default values for all classes"""

    def __init__(self):
        self.param0: str = "test"


class ExampleParams(BaseParams):
    """ example class for data container"""

    def __init__(self, param1: str):
        super().__init__()
        self.param1: str = param1
        self.param2: int = 0

I have many classes like ExampleParams in a py file. I collected them, their docs etc. dynamically with help of inspect and importlib modules but i also have to collect their params and params's types.

Trying to get something like that:

resultdict = {
    "ExampleParams":{"param0":"str","param1":"str","param2":"int"}
}

How can i do that without initializing the classes?

PS1: It is easy when i initialize them but there are many classes and every one have different initialize values. So i have to do it without initializing them i guess.

PS2: Every atrribute's type is declared by typing module

obayhan
  • 1,636
  • 18
  • 35

1 Answers1

2

Without initialization local params like param0 and param2 are not evaluated, so Python interpreter has no information about their existence or type.

The only possibility you have is to collect arguments of __init__ method. Using your example structure:

import inspect

params = []
for parent in ExampleParams.mro()[::-1]:
    parent_init = inspect.getfullargspec(parent.__init__)
    # parent_init.annotations contains annotations if specified in method signature
    for param in parent_init.args:
        if param == 'self':
            continue
        params.append(param)

params = ['param1'] in your case.

ptyshevs
  • 1,602
  • 11
  • 26
  • i have to collect param0, param1, and param 2 too, otherwise it is meaningless. – obayhan Aug 13 '20 at 21:01
  • You can look into `ExampleParams.__init__.__code__` to see all the information interpreter has about `__init__`. For example, `ExampleParams.__init__.__code__.co_names` contains all variable names in local scope. I think the only option is to write python file parser to extract the information of interest. – ptyshevs Aug 13 '20 at 21:44
  • still i cant reach param0, i guess i will use init with help of `paramsclass.__init__.__code__.co_argcount` but getting type hints of attributes still remains – obayhan Aug 13 '20 at 21:53
  • `param0` can be reached only by traversing class `mro`. Type hints are, again, only available for `__init__` arguments, through `inspect.getfullargspec(ExampleParams.__init__).annotations` – ptyshevs Aug 13 '20 at 21:57
  • Not exactly what i wanted but it seems like it is the only solution – obayhan Oct 11 '20 at 22:15