Search code examples
pythonpython-3.xpython-dataclasses

Get List Of Class's Attributes Including Attributes Of Sub Objects - Python


I want to get a list of all the attributes of the class including the attributes used in sub_objects of this class.

Example:

@dataclass
class Phones:
    mobile: Optional[str] = None
    work_phone: Optional[str] = None

@dataclass
class People:
    id: str
    name: str
    phones: Phones

I have People class and one of its attributes is of type Phones. I want to return this list:

['id', 'name', 'mobile', 'work_phone']

I tried __dict__, __annotations__, dir() and more staff but I can't find a way to do it generic and dynamic. My solution is to do a convertor and return this list hardcoded which seems as a bad idea for maintenance.

I want all the attributes with primitive type. (For example I don't want to include phones.)


Solution

  • Thanks to https://stackoverflow.com/users/13526701/noblockhit

    I managed to achieve what I wanted with the next code:

    def list_attributes(entity: object) -> List[str]:
        """
        @returns: List of all the primitive attributes
        """
        attributes: List[str] = []
        entity_attributes = entity.__annotations__.items()
        for attribute_name, attribute_type in entity_attributes:
            if is_dataclass(attribute_type):
                attributes += list_attributes(attribute_type)
            else:
                attributes.append(attribute_name)
        return attributes