Does Mypy disregard constructors?

Viewed 408

I want to use Mypy to warn me when I accidentally change a variable to a different data type. But it seems Mypy ignores anything that happens in the __init__ of my test class. It also ignores a change of an object's attributes to different data types.

Minimal reproducer:

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

Mypy reports no issues for this code.

Am I missing something?

1 Answers

mypy ignores the body of any def statement without type annotations. Annotating any parameter or using the --check-untyped-defs flag causes mypy to inspect __init__ and reject incorrect assignments.

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
Related