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

为何在类方法中仅赋值两个泛型TypeVar之一时mypy会报错?

mypy泛型类中混合绑定与推断TypeVar报错的原因分析

环境:Python 3.10.6,mypy 0.990

可正常通过mypy检查的示例

示例1:单泛型类的empty方法

from typing import Generic, TypeVar

T = TypeVar('T')
class Maybe(Generic[T]):
    def __init__(self, val: T):
        self._val = val
    
    @classmethod
    def empty(cls):
        return cls(None)

示例2:双泛型类的empty方法

from typing import Generic, TypeVar

U = TypeVar('U')
V = TypeVar('V')
class Example(Generic[U, V]):
    def __init__(self, a: U, b: V):
        self._a = a
        self._b = b
    
    @classmethod
    def empty(cls):
        return cls(None, None)

示例3:双泛型类的常规构造方法

from typing import Generic, TypeVar

U = TypeVar('U')
V = TypeVar('V')
class Example(Generic[U, V]):
    def __init__(self, a: U, b: V):
        self._a = a
        self._b = b

    @classmethod
    def both(cls, val: U, b: V):
        return cls(val, b)

触发mypy错误的示例

执行以下代码时,mypy会返回错误:error: Argument 2 to "Example" has incompatible type "None"; expected "V" [arg-type]

from typing import Generic, TypeVar

U = TypeVar('U')
V = TypeVar('V')
class Example(Generic[U, V]):
    def __init__(self, a: U, b: V):
        self._a = a
        self._b = b

    @classmethod
    def first(cls, val: U):
        return cls(val, None)

原因分析

mypy对泛型类的类型推断逻辑是:泛型参数(比如U、V)要么全部通过输入推断,要么被显式绑定到具体类型,不允许部分绑定、部分留空的混合场景。

在报错的first方法中:

  1. 传入的val: U会让mypy将U绑定到具体类型(比如调用时传int,U就是int);
  2. 但V没有任何输入参数来推断其类型,也没有显式指定;
  3. 同时默认的TypeVar不包含None类型,传入None不符合V的类型约束,因此mypy抛出类型不兼容的错误。

而前面通过检查的示例:

  • 示例1、2的empty方法中,所有泛型参数都通过None绑定到NoneType,没有部分绑定的情况;
  • 示例3的both方法中,U和V都通过输入参数完成类型推断,类型完全匹配,因此不会报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 08:50:43