You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何Mypy未检测到Python子类构造函数中的类型提示错误?

Why Isn't Mypy Detecting Errors in Subclass S's __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 T has 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 like T(1, 1) or T(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 return None). Without this hint, Mypy treats the entire method as dynamic, so it ignores the invalid super() 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__:

  1. The unnecessary self argument in super().__init__(self, 1, 2) (you don’t need to pass self to super() calls in Python 3).
  2. The integer 2 passed as the b parameter (which expects Optional[str], not int).
  3. The integer 1 used as an index for self._callback_map (which requires string keys, per typing.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:06:44