Type annotations for full class hierarchy in Python

Question:

Suppose we have the following code:

class Base:
    a: int

class Derived(Base):
    b: int

print(Derived.__annotations__)

Running this script in all recent versions of python will print {'b': <class 'int'>} (that is, the class members we explicitly defined in Derived. In python 3.10, using inspect.get_annotations(Derived) will result in the same output.

My question is, how do I get the type annotations for all the members of Derived? I’d like some function that outputs {'a': <class 'int'>, 'b': <class 'int'>}. This seems like a common enough use case that there should be a built-in function to do this, but I haven’t found any.

I’m running Python 3.10, so recently added functions are good for me.

Answers:

This is a job for typing.get_type_hints, not raw annotation inspection:

import typing

full_hints = typing.get_type_hints(Derived)

This will also resolve string annotations, and recursively replace Annotated[T, ...] with T. Use cases that are interested in non-type-hint annotations can pass include_extras=True to get_type_hints to preserve Annotated annotations.

Answered By: user2357112