检查类型是否为列表

Check if type is a list

我有一些类型(来自 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 的正确方法是什么?

(我使用的是 Python 3.6,代码应该在 mypy --strict 的检查中幸存下来。)

您可以使用 issubclass 来检查这样的类型:

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 issubclass(the_type, 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)