Behavior of "get_type_hints" differs on classes and instances

Originating from this post, I observed the following behavior:

class A[T]:
    a: T

class B[T, P](A[T]):
    b: P

from typing import get_type_hints

# Gets all annotated attributes on B's inheritance chain
get_type_hints(B)  # {'a': T, 'b': P}

# Approaches below only get B's own attributes
get_type_hints(B())  # {'b': P}
B.__annotations__    # {'b': P}
B().__annotations__  # {'b': P}

Is this a bug or a feature? If it is a feature, is there any existing discussion on the rationale of this behavior?

You should not be calling get_type_hints on an class instances, only on the class itself.

The mismatch with __annotations__ is by design and documented: typing — Support for type hints — Python 3.13.0 documentation.

The fact that it does work on arbitrary class instances is probably because it falls back to __annotations__ if it doesn’t precisely know what it’s looking at.

3 Likes