相关疑难解决方法(0)

TypeVar('T', A, B) 和 TypeVar('T', bound=Union[A, B]) 的区别

我正在努力弄清楚以下两个TypeVars之间的区别

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)

python generics type-hinting

16
推荐指数
2
解决办法
5440
查看次数

MyPy 不允许受约束的 TypeVar 是协变的?定义具有约束但协变的键值类型的通用字典

我正在尝试定义一个自定义的通用 dict,它的键是 type T_key,值是 type T_val
我还想对T_keyand施加约束T_val,这样T_key只能是类型AorB或它们的子类。

我该如何实现?

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)

generics covariance python-3.x mypy

2
推荐指数
1
解决办法
1363
查看次数

标签 统计

generics ×2

covariance ×1

mypy ×1

python ×1

python-3.x ×1

type-hinting ×1