我正在努力弄清楚以下两个TypeVar
s之间的区别
from typing import TypeVar, Union
class A: pass
class B: pass
T = TypeVar("T", A, B)
T = TypeVar("T", bound=Union[A, B])
Run Code Online (Sandbox Code Playgroud)
有人想启发我吗?
一个我不明白的例子......
T = TypeVar("T", bound=Union[A, B])
class AA(A):
pass
class X(Generic[T]):
pass
class XA(X[A]):
pass
class XAA(X[AA]):
pass
Run Code Online (Sandbox Code Playgroud)
通过类型检查,但T = TypeVar("T", A, B)
失败了
错误:“X”的类型变量“T”的值不能是“AA”
相关:this question on the difference between Union[A, B]
andTypeVar("T", A, B)
我正在尝试定义一个自定义的通用 dict,它的键是 type T_key
,值是 type T_val
。
我还想对T_key
and施加约束T_val
,这样T_key
只能是类型A
orB
或它们的子类。
我该如何实现?
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]
Run Code Online (Sandbox Code Playgroud)
当我尝试检查这一点时,mypy 在x
,y
和 的注释上给出了错误z
。只有注释w
按预期工作。
generic.py:17: error: …
Run Code Online (Sandbox Code Playgroud)