How to get class variables and type hints?
typing.get_type_hints
is another method that doesn't involve accessing magic properties directly:
from typing import get_type_hints
class Person:
name: str
age: int
get_type_hints(Person)
# returns {'name': <class 'str'>, 'age': <class 'int'>}
These type hints are based on Python annotations. They are available as the __annotations__
property. This goes for classes, as well as functions.
>>> class Person:
... name: str
... age: int
...
>>> Person.__annotations__
{'name': <class 'str'>, 'age': <class 'int'>}
>>> def do(something: str) -> int:
... ...
...
>>> do.__annotations__
{'something': <class 'str'>, 'return': <class 'int'>}