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

如何为该泛型类方法添加正确的mypy类型提示以消除报错?

解决Mypy对多继承类方法的类型检查错误

原代码

from abc import ABC, abstractmethod
from typing import TypeVar

T = TypeVar("T", bound="A")
U = TypeVar("U", bound="ThirdPartyClass")

class ThirdPartyClass:
    """
    这是第三方库中的类,无法修改其实现。
    """
    @classmethod
    def create(cls: type[U]) -> U:
        return cls()

class A(ABC):
    @classmethod
    @abstractmethod
    def f(cls: type[T]) -> T:
        pass

class B(ThirdPartyClass, A):
    @classmethod
    def f(cls) -> T:
        return cls.create()

Mypy报错信息

error: A function returning TypeVar should receive at least one argument containing the same Typevar
error: Incompatible return value type (got "B", expected "T")

问题原因

B.f方法未显式标注cls的类型,导致Mypy无法将返回值的TypeVar T与cls的类型建立关联。尽管B继承自A,但Mypy无法自动推断cls的类型对应TypeVar T的实例,因此抛出类型不匹配的错误。

解决方案

方案一:显式绑定父类的TypeVar

修改B类的f方法,明确标注cls的类型为type[T],让Mypy将T与当前调用的子类类型绑定:

class B(ThirdPartyClass, A):
    @classmethod
    def f(cls: type[T]) -> T:
        return cls.create()

方案二:定义子类专属的TypeVar

如果需要更清晰的类型绑定,可以为B类单独定义TypeVar,避免与父类的T混淆:

class B(ThirdPartyClass, A):
    TB = TypeVar("TB", bound="B")
    @classmethod
    def f(cls: type[TB]) -> TB:
        return cls.create()

两种方案都能让Mypy正确识别cls.create()的返回类型与方法返回值类型一致,消除报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 01:20:41