How to get class variables and type hints?

2020-08-17 18:11发布

问题:

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

回答1:

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


回答2:

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