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 __annotation__ not working with inheritance

I tried this code:

from dataclasses import dataclass

@dataclass
class Data1:
    d11: str
    d12: float

@dataclass
class Data2:
    d21: str
    d22: float

@dataclass
class D3(Data1, Data2): pass

print(D3.__annotations__)

But the annotations for D3 are only {'d11': <class 'str'>, 'd12': <class 'float'>}. Why does it not include annotations for the Data2 fields?

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 :

__annotations__ is for the literal annotations in the class body. It is not intended to represent inheritance at all.
If, for example, D3 actually has annotations only these are visible:

@dataclass
class D3(Data1, Data2):
    a: 3

print(D3.__annotations__)  # {'a': 3}

In your specific case, the __annotations__ are non-empty due to a bug fixed in Python 3.10. Prior to Python 3.10, __annotations__ is only created when there actually are annotations; this means that if a parent class has annotations but a child class does not, the parent annotations are visible via the usual attribute lookup.

Accessing the actual class‘ annotation, i.e. circumventing parent attribute lookup:

@dataclass
class D3(Data1, Data2):
    pass

print(D3.__dict__["__annotations__"])

Will raise KeyError: '__annotations__' in Python 3.9 or earlier.

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