Python get_type_hints not returning parent's annotations of child dataclass

14 views Asked by At

I want to get all fields of a inherited dataclass:

from dataclasses import dataclass, fields
from typing import get_type_hints

@dataclass
class A:
  a: int = 0

@dataclass
class B(A):
  b: int = 0


a = A(a=4)
b = B(a=4, b=5)
print(a.__annotations__)
print(b.__annotations__)

As already in other posts this will print:

{'a': <class 'int'>}
{'b': <class 'int'>}

Some posts like this, suggest the usage of get_type_hints. But in my case doing:

print(get_type_hints(a))
print(get_type_hints(b))

which prints

{'a': <class 'int'>}
{'b': <class 'int'>}

Whereas I would have expected something like {'a': <class 'int'>, 'b': <class 'int'>} in the second print.

Is this correct? Am I doing something wrong? The only way I could extract parent's fields is the following:

print([el.name for el in fields(b)])

Is this the only way?

0

There are 0 answers