当将布尔值与整数混合时,Mypy不会引发错误 [英] Mypy doesn't throw an error when mixing booleans with integers

查看:54
本文介绍了当将布尔值与整数混合时,Mypy不会引发错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用mypy检查Python 3项目.在下面的示例中,我希望mypy将 MyClass 类的构造标记为错误,但事实并非如此.

I am trying to use mypy to check a Python 3 project. In the example below, I want mypy to flag the construction of the class MyClass as an error, but it doesn't.

class MyClass:
    def __init__(self, i:int) -> None:
        pass

obj = MyClass(False)

任何人都可以解释一下吗?IE.解释为什么mypy不报告错误?

Can anyone explain this, please? I.e. explain why mypy does not report an error?

推荐答案

这是因为-不幸的是!-Python中的布尔值是整数.与之类似, bool int 的子类:

It’s because — unfortunately! — booleans in Python are integers. As in, bool is a subclass of int:

In [1]: issubclass(bool, int)
Out[1]: True

因此进行代码类型检查,并且 False 是值为 0 的有效整数.

Hence the code typechecks, and False is a valid integer with value 0.

这篇关于当将布尔值与整数混合时,Mypy不会引发错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆