Get element type of list type [duplicate]

自闭症网瘾萝莉.ら 提交于 2019-12-02 06:44:01

问题


I have some list types (coming from inspect.signature -> inspect.Parameter) and I'd like to get to know the type of their elements. My current solution works but is extremely ugly, see minimal example below:

from typing import List, Type, TypeVar

TypeT = TypeVar('TypeT')

IntList = List[int]
StrList = List[str]

# todo: Solve without string representation and eval
def list_elem_type(list_type: Type[TypeT]) -> Type[TypeT]:
    assert str(list_type)[:11] == 'typing.List'
    return eval(str(list_type)[12:-1]) # type: ignore

assert list_elem_type(IntList) is int
assert list_elem_type(StrList) is str

What would be the correct way to get the type of a List's elements?

(I'm using Python 3.6 and the code should survive a check with mypy --strict.)


回答1:


I believe that you should be able to check the __args__ parameter:

>>> from typing import Dict, List, Type, TypeVar
>>> List[Dict].__args__
(typing.Dict,)
>>> List[int].__args__
(<class 'int'>,)

But note from the docs:

Note The typing module has been included in the standard library on a provisional basis. New features might be added and API may change even between minor releases if deemed necessary by the core developers.

So this probably isn't future proof.



来源:https://stackoverflow.com/questions/51578145/get-element-type-of-list-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!