简体   繁体   English

在参数化泛型中,isinstance和issubclass中的mypy差异从python 3.5到3.6

[英]mypy differences in isinstance and issubclass from python 3.5 to 3.6 in parameterized generics

Before I upgraded to python 3.6 from python 3.5 this worked: 在我从python 3.5升级到python 3.6之前,这个工作:

import typing
issubclass(list, typing.List[int])  # returns True
isinstance([1, 2 ,3], typing.List[int]) # returns True

now in python 3.6 both of these raise the following exception: 现在在python 3.6中,这两个都引发了以下异常:

TypeError: Parameterized generics cannot be used with class or instance checks

Is this new intended behavior or a bug? 这是新的预期行为还是错误? If it is intended how can I perform the checks the code above is doing in python 3.6? 如果打算如何执行检查,上面的代码在python 3.6中进行?

It is intentional, you shouldn't be mixing classes with types as defined in typing , at least, that's the gist of it from what I've understood. 这是故意的,你不应该把类型与typing定义的类型混合起来,至少,这是我所理解的它的要点。 A great deal of discussion for this is contained in the issue #136 Kill __subclasscheck__ which also introduced this change. 关于这一点的大量讨论包含在#136 Kill __subclasscheck__问题中,该问题也引入了这一变化。 The commit message also references how the isinstance / subclass checks will raise TypeError s: 提交消息还引用了isinstance / subclass检查将如何引发TypeError

Using isinstance() or issubclass() raises TypeError for almost everything. 使用isinstance()issubclass()几乎可以引发TypeError There are exceptions: [...] 有例外:[...]

You can compare without specifying the contained types for the generic types, ie: 可以在不指定泛型类型的包含类型的情况下进行比较,即:

isinstance(list, typing.List[int])

but that's the best you can do afaik. 但那是你能做的最好的事情。

If you want to have better type safety in python your options are somewhat limited. 如果你想在python中拥有更好的类型安全性,你的选择有些限制。 A technique I have employed is to subclass list or dict without overriding any properties, methods etc. 我使用的一种技术是子类列表字典而不覆盖任何属性,方法等。

class ListInts(list):
    pass

new_obj = ListInts()
new_obj += [1, 2, 3, 4, 5, 6]
print(isinstance(new_obj, ListInts)

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

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