【问题标题】:Mypy doesn't throw an error when mixing booleans with integers将布尔值与整数混合时,Mypy 不会抛出错误
【发布时间】:2020-03-17 07:25:26
【问题描述】:

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

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

obj = MyClass(False)

谁能解释一下,好吗? IE。解释一下mypy为什么不报错?

【问题讨论】:

标签: python integer boolean mypy


【解决方案1】:

这是因为——不幸的是! — Python 中的布尔值是整数。如,boolint 的子类:

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

因此代码类型检查,False 是一个有效整数,值为0

【讨论】:

    【解决方案2】:

    其实你是对的:

    来自文档(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:错误:“C2”的参数 1 具有不兼容的类型“int”;预期的“布尔” 在 1 个文件中发现 1 个错误(检查 1 个源文件)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-17
      • 2011-11-05
      • 1970-01-01
      • 2011-04-29
      • 1970-01-01
      • 1970-01-01
      • 2011-11-04
      相关资源
      最近更新 更多