使用 TypeVar 时如何处理隐式转换为父类型?
数据小陈
结论
把 __mul__ 的重载改成下面这样:第一个重载接收 other: T,第二个重载接收 other: complex,并把 T 分支放在前面。
@overload
def __mul__(self, other: T) -> Self: ...
@overload
def __mul__(self, other: complex) -> Dummy[complex]: ...
这样在 some_other_func 里,other: T 会命中“同类型”分支,dummy * other 推断为 Dummy[T],不会再和 Dummy[complex] 合并成联合类型。
为什么原来的写法会报错
T = TypeVar("T", float, complex) 的可选类型是 float 和 complex。原来的第一个重载是:
def __mul__(self, other: float | T) -> Self: ...
当 T 可能为 complex 时,float | T 会变成类似 float | complex 的类型,并与第二个重载 other: complex 重叠。再加上 some_other_func 本身是泛型的,类型检查器不能提前假定 T 一定等于 complex,于是会把两个分支的返回类型合起来看,得到 Dummy[T] | Dummy[complex]。而 some_func 只接受 Dummy[T],所以报 invalid-argument-type。
改成 other: T 后,第一个重载明确表示“参数类型与当前 Dummy 的 T 相同”。在泛型函数里,它比 complex 分支更贴近实际参数类型,因此会优先匹配,返回 Self,也就是 Dummy[T]。
修改后的完整示例
from __future__ import annotations
from typing import Generic, Self, TypeVar, overload
T = TypeVar("T", float, complex)
class Dummy(Generic[T]):
def __init__(self, value: T) -> None:
self.value = value
@overload
def __mul__(self, other: T) -> Self: ...
@overload
def __mul__(self, other: complex) -> Dummy[complex]: ...
def __mul__(self, other: float | complex) -> Self | Dummy[complex]:
return Dummy(self.value * other)
def some_func(self, dummy: Dummy[T]) -> None:
pass
def some_other_func(self, dummy: Dummy[T], other: T) -> None:
self.some_func(dummy * other)
如果你的原始代码中 some_func 和 some_other_func 是模块级函数,保留原来的结构即可;关键改动是 __mul__ 的重载参数和顺序。
各类调用的结果
Dummy[float] * float:命中other: T,返回Dummy[float]。Dummy[complex] * float:float可以赋给complex,命中other: T,返回Dummy[complex]。Dummy[complex] * complex:命中other: T,返回Dummy[complex]。Dummy[float] * complex:第一个重载不匹配,命中other: complex,返回Dummy[complex]。
这样两种语义都保住了:
- 乘以
float或同类型T不改变对象类型; - 乘以
complex会转换成Dummy[complex]。
注意事项
- 不要用
other: float | T来表达“乘以 float 或同类型”。它在T=complex时会扩大第一个签名,和other: complex重叠,进而把泛型函数体的推断结果变成联合类型。 - 重载顺序不要反。
other: T放在前面,other: complex放在后面。Python 的数值类型关系里float可以赋给complex,顺序反了容易让Dummy[float] * float被complex分支匹配走。 Self表示当前实例类型;在Dummy[T]上可以理解为Dummy[T],对子类会更精确。如果类型检查器认为实现体返回Dummy(...)不健全,尤其是开启了unsound-return-statement = "error"时,可以把重载返回类型改成Dummy[T]/Dummy[complex],或者在实现体里使用cast、工厂方法构造当前子类;但签名层面的核心改动仍然是上面的重载顺序和参数类型。- 如果某个类型检查器版本对重载解析仍有偏差,可以在
some_other_func里用cast(Dummy[T], dummy * other)做一次收窄,但优先修正__mul__的重载签名。
备注:内容仅供参考。
