-1

How can I get a list of class member variables and their docstring description from a Python class or dataclass?

I have this dataclass

@dataclass
class MyDataClass(BaseDataClass):
    """
    :param var1: Description for var1
    :param var2: Description for var2
    """
    var1: int
    var2: int

and I want to be able to get this information for it:

{
  'var1': ('int', 'Description for var1'), 
  'var2': ('int', 'Description for var2')
}
RaamEE
  • 3,017
  • 4
  • 33
  • 53

1 Answers1

0

To get a list of class member variables and their description I created an empty dataclass with the classmethod

get_user_parameters_dict(cls)

Which parses the class docstring and returns a duct with the member's name, type and description. Since the docstring is not auto-generated, you need to follow the example in the code below. The output of the main section is

Output:

This does not work for a class without properties
This class is probably BaseDataClass. Is it? Actual name: BaseDataClass

var1: int - Description for var1
var2: int - Description for var2


from dataclasses import dataclass
from typing import Dict, Tuple
import re

Code:

@dataclass
class BaseDataClass:
    """
    Example of how to docstring var1 and var2, so reflection works here
    :param var1: Description for var1
    :param var2: Description for var2
    """

    # Example of declaring properties var1 and var2
    # var1: int
    # var2: int

    @classmethod
    def get_user_parameters_dict(cls) -> Dict[str, Tuple[str, str]]:
        properties_descriptions: Dict[str, str] = {}
        regex = r":param *(.*): *(.*)"
        from typing import Generator
        matches: Generator[re.Match, None, None] = re.finditer(regex, cls.__doc__, re.MULTILINE)
        for match in matches:
            prop_name: str = match.groups()[0]
            prop_description: str = match.groups()[1]
            properties_descriptions[prop_name] = prop_description

        dataclass_properties: Dict[str, Tuple[str, str]] = {}
        try:
            dataclass_annotations: Dict[str, object] = cls.__dict__['__annotations__']
            for prop_name, property_type in dataclass_annotations.items():
                dataclass_properties[prop_name] = (property_type.__name__, properties_descriptions[prop_name])

            return dataclass_properties
        except KeyError as ke:
            print('This does not work for a class without properties')



@dataclass
class MyDataClass(BaseDataClass):
    """
    :param var1: Description for var1
    :param var2: Description for var2
    """
    var1: int
    var2: int


if __name__ == '__main__':
    a = BaseDataClass
    try:
        for property_name, property_metadata in BaseDataClass.get_user_parameters_dict().items():
            print(f'{property_name}: {property_metadata[0]} - {property_metadata[1]}')
    except AttributeError as ae:
        print(f'This class is probably TestuserProperties. Is it? Actual name: {BaseDataClass.__name__}')

    print()

    for property_name, property_metadata in MyDataClass.get_user_parameters_dict().items():
        print(f'{property_name}: {property_metadata[0]} - {property_metadata[1]}')
RaamEE
  • 3,017
  • 4
  • 33
  • 53