【发布时间】:2021-07-26 11:51:06
【问题描述】:
我正在尝试使用 typehints 和 Mypy(也是 PyCharm)来强制容器的变化,请参阅,butchered,代码如下:
from typing import TypeVar, Generic
class T: ...
class M(T): ...
class B(M): ...
InMT = TypeVar('InMT', bound=M)
ContraMT = TypeVar('ContraMT', bound=M, contravariant=True)
CoMT = TypeVar('CoMT', bound=M, covariant=True)
class In(Generic[InMT]):
x: InMT
class Contra(Generic[ContraMT]):
x: ContraMT
class Co(Generic[CoMT]):
x: CoMT
t = T()
m = M()
b = B()
m_in: In[M] = In()
m_contra: Contra[M] = Contra()
m_co: Co[M] = Co()
m_in.x = t # mypy: Incompatible types in assignment (expression has type "T", variable has type "M").
m_in.x = m
m_in.x = b
m_contra.x = t # mypy: Incompatible types in assignment (expression has type "T", variable has type "M").
m_contra.x = m
m_contra.x = b
m_co.x = t # mypy: Incompatible types in assignment (expression has type "T", variable has type "M").
m_co.x = m
m_co.x = b
Mypy 发现了一些问题,见上面代码中的 cmets,PyCharm 没有发现!但是我认为 Mypy 遗漏了许多问题,错误地报告了问题,并给出了误导性的错误消息:
-
m_in.x = t的错误消息是错误的,因为变量的类型是InMT而不是M。 -
m_in.x = b应该是一个错误,因为B不是InMT(只有M是)。 -
m_contra.x = t应该不是错误,因为T是ContraMT。 -
m_contra.x = b应该是一个错误,因为B不是ContraMT(只有M或T是)。 -
如上所述,变量的类型为
CoMT而不是M。
我做错了什么;还是我误解了 Mypy 的用途?
【问题讨论】:
标签: python pycharm type-hinting mypy variance