blue note
blue note

Reputation: 29071

Python: Get type of `typing.List`

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?

Upvotes: 11

Views: 7565

Answers (2)

Yacine Nouri
Yacine Nouri

Reputation: 314

For Python 3.8+, use the typing module introspection helpers typing.get_type_hints and typing.get_args:

import typing


class MyType:
    ...


def f(x: typing.List[MyType]):
    ...


if __name__ == "__main__":
    type_hints = typing.get_type_hints(f)
    type_args = typing.get_args(type_hints["x"])
    print(type_args[0])  # prints <class '__main__.MyType'>

Upvotes: 2

L3viathan
L3viathan

Reputation: 27273

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

Upvotes: 12

Related Questions