Python 检查类型是否为列表

Python 检查类型是否为列表,python,python-3.6,typing,Python,Python 3.6,Typing,我有一些来自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

我有一些来自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)
检查类型是否为列表的正确方法是什么

我使用的是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)

为什么不只是:如果类型。。。is list:?@Austin,因为它不适用于输入类型alias。alias.\uuu origin\uuuu似乎是列表类型。我正试图找到一些关于dunder属性的文档。。。编辑:似乎只在3.7中存在。或者更确切地说,在3.6列表中。_origin__;返回None,而List[T]将返回键入。然而,在Python 3.7中,这两个选项似乎都返回List。。。与此相关的: