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)
?
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.
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 ).
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.
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.
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'>}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With