Search code examples
python-3.xinheritancepython-dataclasses

Python sub Dataclass identify inherited attributes


I have 2 dataclass like below:

from dataclasses import dataclass

@dataclass
class Line:
    x: int
    length: int
    color: str

@dataclass
class Rectangle(Line):
    y: int
    height: int
    fill: bool

    def get_dict(self):
        """ return only y, height, and fill """

If I construct a Rectangle object, is it possible to identify which attributes are inherited from the parent data class?

For example, how can I implement the get_dict() method in Rectangle without explicitly typing out all the variables and their values?


Solution

  • Note that dataclasses has an asdict helper function which can be used to serialize a dataclass to a dict object; however, that also includes fields from a superclass like Line for example, so that's probably not what you want here.

    I'd suggest looking into other attributes like Rectangle.__annotations__ which should only have a list of dataclass fields which are exclusive to the class Rectangle. For example:

    from dataclasses import dataclass, asdict
    from typing import Any
    
    
    @dataclass
    class Line:
        x: int
        length: int
        color: str
    
    
    @dataclass
    class Rectangle(Line):
        y: int
        height: int
        fill: bool
    
        def get_dict(self) -> dict[str, Any]:
            """ return only y, height, and fill """
            return {f: getattr(self, f) for f in self.__annotations__}
            # return asdict(self)
    
    
    print(Rectangle(1, 2, 3, 4, 5, 6).get_dict())
    

    Should only return the fields that are exclusive to Rectangle:

    {'y': 4, 'height': 5, 'fill': 6}