这个问题已经有了答案:
我有一些列表类型(来自 inspect.signature -> inspect.Parameter )我想知道它们的元素类型。我目前的解决方案很有效,但非常难看,请参阅下面的最小示例:
inspect.signature
inspect.Parameter
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
正确的方法是什么 List 的元素?
List
(我使用的是Python3.6,代码应该可以通过检查 mypy --strict .)
mypy --strict
我 相信 你应该能够检查 __args__ 参数:
__args__
>>> from typing import Dict, List, Type, TypeVar >>> List[Dict].__args__ (typing.Dict,) >>> List[int].__args__ (<class 'int'>,)
但是来自 docs :
注意 打字模块已临时列入标准库。可能会添加新功能,并且API可能会更改 即使是在核心认为必要的小释放之间 开发商。
所以这可能不是未来的证据。