Search code examples
pythoninheritancepython-decoratorspython-dataclasses

Are the children of Python data classes always data classes themselves?


Suppose I create a parent class and a child class in Python like so:

@dataclass
class MyParent:
    an_attribute: str = "Hello!"
    another_attribute: str = "Dave!"

@dataclass
class MyChild(MyParent):
    another_attribute: str = "Steve!"

Then, clearly, both MyParent and MyChild will be data classes.

But, what happens if I use the following syntax to create MyChild instead?

class MyChild(MyParent):
    another_attribute: str = "Steve!"

Testing on my own machine suggests that, even with the latter syntax, MyChild will also be a data class. But are the children of data classes always data classes themselves? Are there any pitfalls to the latter approach? Is the @dataclass decorator essentially redundant in the definition of the child?


Solution

  • Adding the decorator again is required. Without it, the fields of the child class are not created properly.

    >>> @dataclass
    ... class MyParent:
    ...     an_attribute: str = "Hello!"
    ...     another_attribute: str = "Dave!"
    ... 
    ... class MyChild(MyParent):
    ...     another_attribute: str = "Steve!"
    ... 
    >>> MyChild().another_attribute  # returns the incorrect default
    'Dave!'