为什么 isinstance([1, 2, 3], List[str]) 的计算结果为真?

Why does isinstance([1, 2, 3], List[str]) evaluate to true?

我正在使用 python3.5 的新类型提示/输入模块进行一些尝试,试图找到一种方法来确认提示类型是否等于变量的实际类型并遇到让我很吃惊的东西。

>>> from typing import List
>>> someList = [1, 2, 3]
>>> isinstance(someList, List[str])
True

继续寻找一种方法来比较变量和它的提示类型我也试过这个:

>>> anotherList = ["foo", "bar"]
>>> type(anotherList) is List[str]
False

谁能解释为什么前者的计算结果是 True

接下来,是否有一种可靠的方法来检查变量的类型是否等于来自输入模块的类型?

isinstance does not do real PEP 484 type checking. The documentation 顺便指出:

In general, isinstance() and issubclass() should not be used with types.

typing 模块,以及它所基于的 collections.abcabc 模块,使用广泛的 __instancecheck__ and __subclasscheck__ 魔法来制作 isinstanceissubclass 举止得体。但他们在支持你的案子方面做得不够。支持它也不是他们的目标。

is there a sound way to check if a variable's type is equal to a type coming from the typing module?

你不是在寻找类型 equality。正如您自己注意到的,[1, 2, 3] 的类型是 list,它不 等于 List[str],也不等于 List[int]。您正在寻找类型 checking,这要复杂得多。

考虑一下:

def my_function():
    # ... 1000 lines of very complicated code ...

print(isinstance(my_function, Callable[[], int]))

您希望此程序打印什么?你不能指望 isinstance 在运行时深入研究 my_function 并推断它总是 returns int。这在Python中是行不通的。您需要一个可以访问 my_function 结构的“编译”时间类型检查器,或者显式类型注释,或者——很可能——两者都需要。