Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get class variables and type hints?

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

like image 793
blue_note Avatar asked Oct 16 '18 14:10

blue_note


People also ask

How do you type hints in Python?

Here's how you can add type hints to our function: Add a colon and a data type after each function parameter. Add an arrow ( -> ) and a data type after the function to specify the return data type.

How do you Typehint a class in Python?

Python Type Hints - How to Specify a Class Rather Than an Instance Thereof. In a type hint, if we specify a type (class), then we mark the variable as containing an instance of that type. To specify that a variable instead contains a type, we need to use type[Cls] (or the old syntax typing. Type ).

Does Python have type hints?

Python's type hints provide you with optional static typing to leverage the best of both static and dynamic typing. Besides the str type, you can use other built-in types such as int , float , bool , and bytes for type hintings. To check the syntax for type hints, you need to use a static type checker tool.

How do you determine the type of a variable in Python?

To get the type of a variable in Python, you can use the built-in type() function. In Python, everything is an object. So, when you use the type() function to print the type of the value stored in a variable to the console, it returns the class type of the object.


2 Answers

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'>}
like image 107
Brendan Avatar answered Sep 19 '22 23:09

Brendan


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'>}
like image 29
Remco Haszing Avatar answered Sep 19 '22 23:09

Remco Haszing