【发布时间】:2019-01-05 18:26:55
【问题描述】:
我有一些类型(来自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 进行检查。)
【问题讨论】:
-
为什么不直接:
if type(...) is list:? -
@Austin 因为这不适用于
typing类型别名 -
暂时,
alias.__origin__似乎是list类型。不过,我正在尝试查找有关此 dunder 属性的一些文档...编辑:似乎仅适用于 3.7。 -
或者更确切地说,在 3.6 中
List.__origin__返回None,而List[T]将返回typing.List,然而,这两个似乎在 Python 3.7 中都返回list... 呃
标签: python python-3.6 typing