将布尔值与整数混合时,Mypy 不会抛出错误
Mypy doesn't throw an error when mixing booleans with integers
我正在尝试使用 mypy 检查 Python 3 项目。在下面的示例中,我希望 mypy 将 class MyClass
的构造标记为错误,但它没有。
class MyClass:
def __init__(self, i:int) -> None:
pass
obj = MyClass(False)
有人能解释一下吗? IE。解释为什么mypy不报错?
这是因为——不幸的是! — Python 中的布尔值是整数。如,bool
是 int
的子类:
In [1]: issubclass(bool, int)
Out[1]: True
因此代码会进行类型检查,False
是一个有效的整数,值为 0
。
其实你是对的:
来自文档(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"
在 1 个文件中发现 1 个错误(已检查 1 个来源
评论 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
似乎出于某种原因布尔值被视为整数
以及解释:
https://github.com/python/mypy/issues/1757
这意味着
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: 错误:参数 1 到 "C2" 的类型不兼容 "int";预计 "bool"
在 1 个文件中发现 1 个错误(已检查 1 个源文件)
我正在尝试使用 mypy 检查 Python 3 项目。在下面的示例中,我希望 mypy 将 class MyClass
的构造标记为错误,但它没有。
class MyClass:
def __init__(self, i:int) -> None:
pass
obj = MyClass(False)
有人能解释一下吗? IE。解释为什么mypy不报错?
这是因为——不幸的是! — Python 中的布尔值是整数。如,bool
是 int
的子类:
In [1]: issubclass(bool, int)
Out[1]: True
因此代码会进行类型检查,False
是一个有效的整数,值为 0
。
其实你是对的:
来自文档(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"
在 1 个文件中发现 1 个错误(已检查 1 个来源
评论 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
似乎出于某种原因布尔值被视为整数 以及解释: https://github.com/python/mypy/issues/1757
这意味着
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: 错误:参数 1 到 "C2" 的类型不兼容 "int";预计 "bool" 在 1 个文件中发现 1 个错误(已检查 1 个源文件)