Mypy doesn't throw an error when mixing booleans with integers

亡梦爱人 提交于 2021-02-01 20:41:48

问题


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)

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


回答1:


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

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




回答2:


Actually you are right:

From the docs (contents of test.py):

class C2:
    def __init__(self, arg: int):
        self.var = arg


c2 = C2(True)
c2 = C2('blah')

mypy test.py
$>test.py:11: error: Argument 1 to "C2" has incompatible type "str"; expected "int"

Found 1 error in 1 file (checked 1 source

Commenting the c2 = C2('blah')

class C2:
    def __init__(self, arg: int):
        self.var = arg


c2 = C2(True)

mypy test.py

Success: no issues found in 1 source file

Seems like Booleans are taken as integers for some reason And the explanation: https://github.com/python/mypy/issues/1757

which means

class C2:
def __init__(self, arg: bool):
    self.var = arg

# tHIx WORKS FINE
c2 = C2(true)
# tHIx DOES NOT WORK
c2 = C2(0)

test.py:10: error: Argument 1 to "C2" has incompatible type "int"; expected "bool" Found 1 error in 1 file (checked 1 source file)



来源:https://stackoverflow.com/questions/58973631/mypy-doesnt-throw-an-error-when-mixing-booleans-with-integers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!