You need to enable JavaScript to run this app. mypy为何不识别继承关系?传入子类列表报类型不兼容错误
优惠活动
大模型
产品
解决方案
定价
更多

mypy为何不识别继承关系?传入子类列表报类型不兼容错误

问题原因说明

这个报错既不是mypy的bug,也不是你漏了配置,核心是**Python可变泛型容器的不变性(invariance)**规则:

  • 虽然Child是Parent的子类,但List[Child]不是List[Parent]的子类
  • 这是因为List是可变容器,假设允许List[Child]赋值给List[Parent],后续就可以合法地往List[Parent]里插入任意Parent实例(包括非Child的其他子类),导致原List[Child]出现类型不匹配的元素,破坏类型安全。
修复方案

方案1:使用协变的不可变序列类型(推荐)

collections.abc.Sequence是只读的序列类型,默认支持协变:Sequence[Child]是Sequence[Parent]的合法子类。只需要把ParentList构造函数的入参类型从List[Parent]改为Sequence[Parent]即可,修改后代码可正常通过类型检查:

from collections.abc import Sequence
from typing import List


class Parent:
    def my_method(self) -> int:
        return 42


class Child(Parent):
    def __init__(self, some_int: int):
        self.some_int = some_int

    def my_method(self) -> int:
        return self.some_int


class ParentList(Sequence[Parent]):
    # 入参改为Sequence类型
    def __init__(self, parent_list: Sequence[Parent]):
        self.parent_list = parent_list

    def __getitem__(self, index):
        return self.parent_list[index]
    
    def __len__(self):
        return len(self.parent_list)

class ChildList(ParentList):
    def __init__(self, child_list: Sequence[Child]):
        super().__init__(child_list)

方案2:自定义协变泛型容器

如果需要保留ParentList的泛型能力,可以自定义协变的泛型类:

from collections.abc import Sequence
from typing import TypeVar, Generic

T_co = TypeVar('T_co', bound=Parent, covariant=True)

class Parent:
    def my_method(self) -> int:
        return 42

class Child(Parent):
    def __init__(self, some_int: int):
        self.some_int = some_int
    def my_method(self) -> int:
        return self.some_int

class ParentList(Sequence[T_co], Generic[T_co]):
    def __init__(self, parent_list: Sequence[T_co]):
        self.parent_list = parent_list
    def __getitem__(self, index):
        return self.parent_list[index]
    def __len__(self):
        return len(self.parent_list)

# ChildList可以直接绑定Child类型
class ChildList(ParentList[Child]):
    pass

方案3:临时绕过检查(不推荐)

如果你确认后续不会修改传入的列表,只是需要临时绕开mypy检查,可以给报错行加忽略注释:

super().__init__(child_list)  # type: ignore[arg-type]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 21:45:07