Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

dataclass behaviour in derived class

I ran into this bizzare behaviour of dataclasses when intermixed with inheritance/type annotations:

>>> @dataclass
... class Base:
...     a: int = 10
...
>>>
>>> @dataclass
... class Derived(Base):
...     a = 20
...
>>>
>>> Derived.a
20
>>> Derived().a
10

Note that if I add annotation on a in Derived, then things behave reasonably.

What exactly is going on here?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The documentation mentions the following:

The dataclass() decorator examines the class to find fields. A field is defined as a class variable that has a type annotation. […]

Hence, in the definition of Derived, a = 20 is not identified as a field and thus it is not added to the __init__ method of the class. When creating an instance of that class, it will use the original parameter definition from Base which has 10 as a default value.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading