确定对象的类型是否与通过 typing 模块定义的嵌套类型匹配

Determine if the type of an object matches a nested type defined via the typing module

使用 typing 模块,可以指定任意嵌套类型,例如 List[str]Dict[str, Dict[str, float]]。有没有办法判断对象的类型是否匹配这样的类型?类似于

>>> from typing import List
>>> isinstance(['a', 'b'], List[str])
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
#   File "/home/cbieganek/anaconda3/lib/python3.6/typing.py", line 1162, in __instancecheck__
#     return issubclass(instance.__class__, self)
#   File "/home/cbieganek/anaconda3/lib/python3.6/typing.py", line 1148, in __subclasscheck__
#     raise TypeError("Parameterized generics cannot be used with class "
# TypeError: Parameterized generics cannot be used with class or instance checks

我真的没想到 isinstance() 会为此工作,但我想知道是否还有其他可接受的方法。

泛型作为类型 hinting 的一部分出现在 python 中。使用 List[str] 的便捷方法是变量或函数参数的类型提示:

my_list: List[str] = ['1', '2']

def do_something(strings: List[str])->None:
    ...

大多数现代 IDE,如 PyCharm 或 Athom 都有支持对 python 代码进行静态类型检查的插件,另请参阅 mypy。如果需要严格 运行 时间类型检查,可以遍历列表并检查每个项目类型,但这不是一个好的设计。