29

Assume I define a class with class level variables with type hints (e.g. something like the new python 3.7 dataclasses)

class Person:
    name: str
    age: int

    def parse_me(self):
        "what do I do here??"        

How can I get the pairs of (variable name, variable type)?

martineau
  • 119,623
  • 25
  • 170
  • 301
blue_note
  • 27,712
  • 9
  • 72
  • 90
  • 2
    Possible duplicate of [How can I get Python 3.7 new dataclass field types?](https://stackoverflow.com/questions/51946571/how-can-i-get-python-3-7-new-dataclass-field-types) – Maor Refaeli Oct 16 '18 at 15:00
  • 3
    Not a duplicate IMO. The other question is about the dataclasses for which there are different methods to extract annotations. – krassowski Sep 11 '19 at 21:13

2 Answers2

47

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'>}
Gringo Suave
  • 29,931
  • 6
  • 88
  • 75
Brendan
  • 1,905
  • 2
  • 19
  • 25
24

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'>}
Remco Haszing
  • 7,178
  • 4
  • 40
  • 83