与 mypy 和 pytorch 不安全地重叠签名

问题描述

我在使用 mypy 和 PyTorch 时遇到了问题,我不确定这是错误还是我不明白的问题。在此示例中,我尝试为可以乘以张量的自定义类编写 __mul____rmul__。但是,当我编写 __rmul__ 的签名时,我从 mypy 收到错误警告:Signatures of "__rmul__" of "TestClass" and "__mul__" of "Tensor" are unsafely overlapping。这是我的 MWE,显示错误

from torch import Tensor

class TestClass:
    def __rmul__(self,other: Tensor) -> "TestClass"
        ...

我最好的猜测是 Tensor.__mul__ 的签名为 __mul__(self,other) -> Tensor,而 other 被隐式定义为 Any。因此,mypy 无法判断 tensor_var * test_class_var 是否会产生 TensorTestClass 类型的对象,即使我知道它会产生 TestClass。这个解释正确吗?如果是这样,是否有任何方法可以抑制此输出,或通知 mypy Tensor.__mul__ 实际上不适用于 TestClass 的实例?

有趣的是,这只发生在 __rmul__ 上。定义 TestClass.__mul__ 不会导致此问题。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)