为何Mypy未检测到Python子类构造函数中的类型提示错误?
__init__ Method? Great question! The core issue here boils down to Mypy's default behavior for unannotated functions: any function without type annotations (including return type hints) is treated as dynamically typed, meaning Mypy skips strict type validation for its internal code.
Let’s break this down with your code:
- Your base class
Thas a fully annotated__init__method (def __init__(self, a: int, b: str = None) -> None), so Mypy rigorously checks all calls to it—this is why lines likeT(1, 1)orT(1, b=2)correctly trigger errors in your output. - However, your subclass
S's__init__method lacks a return type annotation (even though__init__should always returnNone). Without this hint, Mypy treats the entire method as dynamic, so it ignores the invalidsuper()call and dictionary index inside it.
How to Fix This
Simply add the return type annotation to S's __init__ method, like so:
class S(T): def __init__(self) -> None: # Added return type annotation here super().__init__(self, 1, 2) self._callback_map[1] = "TOTO"
Once you make this change, Mypy will catch all the hidden errors in S's __init__:
- The unnecessary
selfargument insuper().__init__(self, 1, 2)(you don’t need to passselftosuper()calls in Python 3). - The integer
2passed as thebparameter (which expectsOptional[str], notint). - The integer
1used as an index forself._callback_map(which requires string keys, pertyping.Dict[str, str]).
Why This Works
Mypy uses type annotations as a signal to enable strict checking for a function. For special methods like __init__, even though the self parameter doesn’t need an explicit annotation, adding -> None tells Mypy to apply its full type-checking rules to the method’s body.
内容的提问来源于stack exchange,提问作者Olivier RD

