我正在尝试定义一个自定义通用字典,其键的类型T_key
并且值的类型T_val
.
我也想限制一下T_key
and T_val
,使得T_key
只能是类型A
or B
或其子类。
我该如何实现这个目标?
from typing import TypeVar, Generic
class A: ...
class B: ...
class Asub(A): ...
class Bsub(B): ...
T_key = TypeVar('T_key', A, B, covariant=True)
T_val = TypeVar('T_val', A, B, covariant=True)
class MyDict(Generic[T_key, T_val]): ...
w: MyDict[ A, B]
x: MyDict[ A, Bsub]
y: MyDict[Asub, B]
z: MyDict[Asub, Bsub]
当我尝试检查这一点时,mypy 在注释上给出了错误x
, y
and z
。仅注释为w
按预期工作。
generic.py:17: error: Value of type variable "T_val" of "MyDict" cannot be "Bsub"
generic.py:18: error: Value of type variable "T_key" of "MyDict" cannot be "Asub"
generic.py:19: error: Value of type variable "T_key" of "MyDict" cannot be "Asub"
generic.py:19: error: Value of type variable "T_val" of "MyDict" cannot be "Bsub"
我不明白为什么Asub
不是有效类型T_key
即使covariant=True
指定的。
我在这里缺少什么?
mypy 版本:0.630