26

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)?

2

2 Answers 2

43

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'>}
1
  • 2
    It also renders "forward" annotations given as strings. Jan 8, 2020 at 3:36
22

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'>}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.