我有一些类型(来自inspect.signature
->;inspect.Parameter
),我想检查它们是否是列表。我目前的解决方案很有效,但非常难看,请参见下面的最小示例:
from typing import Dict, List, Type, TypeVar
IntList = List[int]
StrList = List[str]
IntStrDict = Dict[int, str]
TypeT = TypeVar('TypeT')
# todo: Solve without using string representation of type
def is_list_type(the_type: Type[TypeT]) -> bool:
return str(the_type)[:11] == 'typing.List'
assert not is_list_type(IntStrDict)
assert not is_list_type(int)
assert not is_list_type(str)
assert is_list_type(IntList)
assert is_list_type(StrList)
检查类型是否为List
的正确方法是什么?你知道吗
(我使用的是python3.6,代码应该能够通过mypy --strict
的检查。)
可以使用
issubclass
检查以下类型:相关问题 更多 >
编程相关推荐