Home > Net >  Type annotations for full class hierarchy in Python
Type annotations for full class hierarchy in Python

Time:01-02

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.

CodePudding user response:

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.

(There is currently a documentation error saying that get_type_hints does not include base class annotations. This documentation error was introduced by someone who mixed up the get_type_hints behavior with an unrelated issue.)

  • Related