Mypy 是否忽略构造函数?

unk*_*000 5 python types mypy

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

最小再现器:

class Foo:
    blah: int
    def __init__(self):
        self.blah = 'asdf'
Run Code Online (Sandbox Code Playgroud)

Mypy报告此代码没有问题。

我错过了什么吗?

Mis*_*agi 4

mypy忽略任何没有类型注释的语句主体def。注释任何参数或使用--check-untyped-defs标志都会导致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
Run Code Online (Sandbox Code Playgroud)