获取列表类型的元素类型
Get element type of list type
我有一些列表类型(来自 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
元素类型的正确方法是什么?
(我使用的是 Python 3.6,代码应该在 mypy --strict
的检查中幸存下来。)
我相信您应该能够检查__args__
参数:
>>> from typing import Dict, List, Type, TypeVar
>>> List[Dict].__args__
(typing.Dict,)
>>> List[int].__args__
(<class 'int'>,)
但来自 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.
所以这可能不是未来的证明。
我有一些列表类型(来自 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
元素类型的正确方法是什么?
(我使用的是 Python 3.6,代码应该在 mypy --strict
的检查中幸存下来。)
我相信您应该能够检查__args__
参数:
>>> from typing import Dict, List, Type, TypeVar
>>> List[Dict].__args__
(typing.Dict,)
>>> List[int].__args__
(<class 'int'>,)
但来自 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.
所以这可能不是未来的证明。