为何在类方法中仅赋值两个泛型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方法中:
- 传入的
val: U会让mypy将U绑定到具体类型(比如调用时传int,U就是int); - 但V没有任何输入参数来推断其类型,也没有显式指定;
- 同时默认的TypeVar不包含
None类型,传入None不符合V的类型约束,因此mypy抛出类型不兼容的错误。
而前面通过检查的示例:
- 示例1、2的
empty方法中,所有泛型参数都通过None绑定到NoneType,没有部分绑定的情况; - 示例3的
both方法中,U和V都通过输入参数完成类型推断,类型完全匹配,因此不会报错。
内容的提问来源于stack exchange,提问作者Blake
相关产品推荐
相关产品推荐

