Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Get type of `typing.List`

Tags:

python

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?

like image 511
blue_note Avatar asked Nov 02 '17 14:11

blue_note


People also ask

What is list from typing in Python?

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.

What is type hint Python?

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.

Does Python enforce type hints?

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 .

When did Python get type annotations?

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.


1 Answers

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'>
like image 72
L3viathan Avatar answered Oct 09 '22 12:10

L3viathan