I'm trying to define a custom generic dict, whose keys are of type T_key
and values are of type T_val
.
I also want to put constraints on T_key
and T_val
, such that T_key
can only be of type A
or B
or their subclass.
How do I accomplish this?
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]
When I try to check this, mypy gives errors on annotations of x
, y
and z
. Only the annotation for w
works as expected.
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"
I don't understand why Asub
is not a valid type for T_key
even with covariant=True
specified.
What am I missing here?
mypy version: 0.630