I have annotated the arguments of a function as
import typing
def f(x: typing.List[MyType]):
...
By inspecting the parameter arguments, I get for the type of x
, an instance of typing.GenericMeta
which is, correctly, printed as typing.List[MyType]
How can I get the List
and MyType
from this object?
List. Lists are used to store multiple items in a single variable. Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.
Introduction to Python type hints It means that you need to declare types of variables, parameters, and return values of a function upfront. The predefined types allow the compilers to check the code before compiling and running the program.
The Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as type checkers, IDEs, linters, etc. This module provides runtime support for type hints. The most fundamental support consists of the types Any , Union , Callable , TypeVar , and Generic .
Annotations were introduced in Python 3.0, and it's possible to use type comments in Python 2.7. Still, improvements like variable annotations and postponed evaluation of type hints mean that you'll have a better experience doing type checks using Python 3.6 or even Python 3.7.
If you want to get MyType
, you can find it under .__args__
:
import typing
def f(x: typing.List[MyType]):
...
print(f.__annotations__["x"].__args__[0]) # prints <class '__main__.MyType'>
List
(i.e. typing.List
) is accessible from .__base__
, and the actual list class comes from .__orig_bases__
:
print(f.__annotations__["x"].__base__) # prints typing.List[float]
print(f.__annotations__["x"].__orig_bases__[0]) # prints <class 'list'>
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