Search code examples
pythontypesconstructormypy

Template / Generic user-defined classes in python weird behavior


When I write the following code, mypy issues an error (like it should):

from typing import TypeVar, Generic, List
Data = TypeVar("Data")
class State(Generic[Data]):
    def __init__(self) -> None:
        self.d: Data = 8.9
s = State[int]()

When I remove the (completely redundant, right?) -> None part from the ctor, mypy ignores the type mismatch. Why is that? (note that this is not a duplicate of this)


Solution

  • Mypy only checks functions that are typed. By removing the -> None you are making your __init__ untyped and therefore mypy doesn't check that function.

    This is covered in the common issues section of the mypy wiki: https://mypy.readthedocs.io/en/stable/common_issues.html#no-errors-reported-for-obviously-wrong-code

    There are several common reasons why obviously wrong code is not flagged as an error.

    The function containing the error is not annotated. Functions that do not have any annotations (neither for any argument nor for the return type) are not type-checked, and even the most blatant type errors (e.g. 2 + 'a') pass silently. The solution is to add annotations. Where that isn’t possible, functions without annotations can be checked using --check-untyped-defs.