In the following code:
class A[T]:
a: T
class B[T, P](A[T]):
b: P
B[int, str]().__annotations__ # {'b': P}
Is there a way to get the full annotations? i.e.
{'a': T, 'b': P}
In the following code:
class A[T]:
a: T
class B[T, P](A[T]):
b: P
B[int, str]().__annotations__ # {'b': P}
Is there a way to get the full annotations? i.e.
{'a': T, 'b': P}
Self solved:
Instead of accessing __annotations__
, use typing.get_type_hints()
on the class. Not instance.
from typing import get_type_hints
# CORRECT
get_type_hints(B) # {'a': T, 'b': P}
# All these below are WRONG
get_type_hints(B()) # {'b': P}
B.__annotations__ # {'b': P}
B().__annotations__ # {'b': P}
Note that B.__annotations__
can be correct if you truly only want the annotations directly on class for e.g. a dataclass
-like. But accessing it on an instance is always wrong.