简体   繁体   English

为什么isinstance([1,2,3],List [str])评估为真?

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

I was playing around a bit with the new type hinting / typing module with python3.5 trying to find a way to confirm if the hinted type is equal to the actual type of the variable and came across something that rather surprised me. 我正在使用python3.5的新类型提示/输入模块玩一下,试图找到一种方法来确认提示类型是否等于变量的实际类型并且遇到了令我感到惊讶的事情。

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

Continuing my search for finding a way to compare a variable to it's hinted type I've also tried this: 继续我的搜索找到一种方法来比较变量与它的暗示类型我也试过这个:

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

Would anyone be able to explain why exactly the former evaluates to True? 有人能够解释为什么前者评估为True吗?

And continuing onwards, is there a sound way to check if a variable's type is equal to a type coming from the typing module? 继续向前,有没有一种方法来检查变量的类型是否等于来自打字模块的类型?

isinstance does not do real PEP 484 type checking. isinstance不进行真正的PEP 484类型检查。 The documentation notes this in passing: 文档记录了这一点:

In general, isinstance() and issubclass() should not be used with types. 通常, isinstance()issubclass()不应与类型一起使用。

The typing module, as well as the collections.abc and abc modules it's based on, use extensive __instancecheck__ and __subclasscheck__ magic to make isinstance and issubclass behave reasonably. typing模块,以及它所基于的collections.abcabc模块,使用广泛的__instancecheck____subclasscheck__ magic来使isinstanceissubclass表现得相当合理。 But they're not doing enough to support your case. 但他们没有做足以支持你的案子。 Nor is it their goal to support it. 他们的目标也不是支持它。

is there a sound way to check if a variable's type is equal to a type coming from the typing module? 有没有一种方法可以检查变量的类型是否等于来自输入模块的类型?

You're not looking for type equality . 你不是在寻找类型相等 As you have noted yourself, the type of [1, 2, 3] is list , which is not equal to List[str] , nor to List[int] . 正如您已经注意到的那样, [1, 2, 3]list ,它不等于 List[str] ,也不等于 List[int] You're looking for type checking , which is much more complicated. 你正在寻找类型检查 ,这要复杂得多。

Consider this: 考虑一下:

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

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

What would you expect this program to print? 您希望这个程序打印什么? You can't expect isinstance to dig into my_function at runtime and infer that it always returns int . 你不能指望isinstance在运行时挖掘my_function并推断它总是返回int This is not feasible in Python. 这在Python中是不可行的。 You need either a “compile” time type checker that has access to the structure of my_function , or explicit type annotations, or—most likely—both. 您需要一个可以访问my_function结构的“编译”时间类型检查器,或者显式类型注释,或者最有可能两者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM