bux
bux

Reputation: 7739

Retrieve typing.List[X] type

For the following typing:

import typing
foo: typing.List[int] = []

How to retrieve type of items in foo list (through type hinting) ? Result must be <class 'int'>.

Upvotes: 1

Views: 96

Answers (1)

user459872
user459872

Reputation: 24582

Not sure if you are looking for something like this.

import sys
import typing

foo: typing.List[int] = []
foo_one: typing.Tuple[float] = ()

def _get_type_of_item(param):
    """
    typing.get_type_hints(obj[, globals[, locals]]):

    Return a dictionary containing type hints for a function, method, module or class object.
    """
    return typing.get_type_hints(sys.modules[__name__])[param].__args__


print(_get_type_of_item('foo')) # this will print (<class 'int'>,)
print(_get_type_of_item('foo_one')) # this will print (<class 'float'>,)

Upvotes: 1

Related Questions