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

Pyright/Pylance类型提示报错:Grid子类基类互斥不兼容的原因及正确实现方式

Pyright/Pylance类型提示报错:Grid子类基类互斥不兼容的原因及正确实现方式

我正在尝试学习如何使用基类和继承。我的代码运行正常,但却收到了类型检查错误。我到底是遇到了类型检查器的问题、类型提示的问题,还是代码本身存在实质性问题?

我先尝试实现了一个继承自抽象基类Sequence(还有ABC——这有必要吗?)的泛型类,然后创建了将序列具体化为列表或元组的子类。Pylance/pyright对此没有异议,代码运行也没问题:

from __future__ import annotations
from abc import ABC
from collections.abc import Iterable, Sequence

class Row[T](Sequence[T], ABC):
    def __init__(self, iterable: Iterable[T]):
        ...

class Row_Mutable[T](list[T], Row[T]):
    def __init__(self, iterable):
        super().__init__(iterable)

class Row_Immutable[T](tuple[T], Row[T]):
    def __init__(self, iterable):
        super().__init__(iterable)

row_mut_int: Row_Mutable[int] = Row_Mutable(range(10))
row_mut_str: Row_Mutable[str] = Row_Mutable('abcdefg')
row_imm_int: Row_Immutable[int] = Row_Immutable(range(10))
row_imm_str: Row_Immutable[str] = Row_Immutable('abcdefg')

现在我想实现一个二维版本,也就是“序列的序列”,所以子类应该是列表的列表和元组的元组:

class Grid[T](Sequence[Sequence[T]], ABC):
    def __init__(self, iterable: Iterable[Iterable[T]]):
        ...

class Grid_Mutable[T](list[list[T]], Grid[T]):
    def __init__(self, iter_of_iter):
        super().__init__(list(row) for row in iter_of_iter)

class Grid_Immutable[T](tuple[tuple[T]], Grid[T]):
    def __init__(self, iter_of_iter):
        super().__init__(tuple(row) for row in iter_of_iter)

现在Pylance/pyright对类定义抛出了错误:

Base classes of Grid_Mutable are mutually incompatible
Base class "Grid[T@Grid_Mutable]" derives from "Sequence[Sequence[T@Grid_Mutable]]" which is incompatible with type "Sequence[list[T@Grid_Mutable]]"

元组版本也有类似的错误。

为什么Sequence[Sequence[T]]和Sequence[list[T]]会不兼容?我应该如何正确编码和添加类型提示来实现这样的结构?

Copilot建议使用T = TypeVar('T')的形式而不是Grid[T],这稍微改变了错误,但并没有解决问题。我正在使用Python 3.13,不关心向后兼容性——更关注最佳实践和Python风格。

备注:内容来源于stack exchange,提问作者Jacktose

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 14:14:34