Mypy 会忽略构造函数吗?

Does Mypy disregard constructors?

当我不小心将变量更改为不同的数据类型时,我想使用 Mypy 来警告我。 但似乎 Mypy 忽略了我测试 class 的 __init__ 中发生的任何事情。 它还会忽略对象属性对不同数据类型的更改。

最小复制器:

class Foo:
    blah: int
    def __init__(self):
        self.blah = 'asdf'

Mypy reports no issues 此代码。

我是不是漏掉了什么?

mypy 忽略任何没有类型注释的 def 语句的主体。注释任何参数或使用 --check-untyped-defs flag 会导致 mypy 检查 __init__ 并拒绝不正确的分配。

class Foo:
    blah: int
    blub: int

    # annotated parameter `blub` and/or return `->` trigger inspection
    def __init__(self, blub: int = 42) -> None:
        self.blah = 'asdf'  # error: Incompatible types in assignment (expression has type "str", variable has type "int")
        self.blub = blub