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

重写Python UserDict的__or__方法时mypy提示返回类型不兼容

解决UserDict子类重写__or__方法时mypy返回类型不兼容问题

mypy报错的核心原因是:父类UserDict的__or__方法返回的是泛型化的UserDict[Union[K, _T1], Union[V, _T2]],而你的CustomDict是UserDict[str, Any]的具体子类。虽然子类实例可以兼容父类类型,但mypy对泛型方法的重写有更严格的类型检查,需要明确返回类型与父类的泛型约束匹配。

方案一:使用Self类型(Python 3.11+推荐)

Python 3.11引入的Self类型注解可直接指代当前类的实例类型,能让mypy准确识别返回类型的兼容性:

from collections import UserDict
from typing import Any, Self


class CustomDict(UserDict[str, Any]):
    def __init__(self):
        self.data = {}

    def __or__(self, other: Any) -> Self:
        if isinstance(other, CustomDict):
            return other
        return NotImplemented

方案二:显式标注父类的具体泛型返回类型

如果需要兼容更低版本Python,可直接将返回类型标注为UserDict[str, Any]——CustomDict作为它的子类,类型上完全兼容:

from collections import UserDict
from typing import Any


class CustomDict(UserDict[str, Any]):
    def __init__(self):
        self.data = {}

    def __or__(self, other: Any) -> UserDict[str, Any]:
        if isinstance(other, CustomDict):
            return other
        return NotImplemented

额外说明

  • 返回NotImplemented是正确的运算符重载规范:当传入不兼容类型时,该返回值会让Python自动尝试调用对方的__ror__方法。
  • 你关于「重写方法可返回父类返回类型子类」的理解没错,只是泛型场景下需要让类型检查器明确识别这种兼容性,上述两种方案均可解决问题。

内容的提问来源于stack exchange,提问作者Yotam Hochman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 04:34:57