mypy错误:Python数据类中的+操作数类型不支持(”Self”和”A”)[运算符]

huangapple go评论86阅读模式
英文:

mypy error: Unsupported operand types for + ("Self" and "A") [operator] in Python dataclasses

问题

我正在研究一个依赖于严格类型提示的项目。我正在处理的最小代码示例将返回此mypy错误:

error.py:15: error: 不支持的操作数类型+(“Self”和“A”)[operator]
            return self + rhs.to_A()
                          ^~~~~~~~~~

可以有人解释一下为什么会出现这种情况吗?

英文:

I'm working on a project that relies on strict type hinting. The minimal code example that I'm working on will return this mypy error:

error.py:15: error: Unsupported operand types for + ("Self" and "A")  [operator]
            return self + rhs.to_A()
                          ^~~~~~~~~~
from __future__ import annotations

from dataclasses import dataclass
from typing_extensions import Self


@dataclass
class A:
    num: int = 0

    def __add__(self, rhs: Self) -> Self:
        return type(self)(self.num + rhs.num)

    def add_B(self, rhs: B) -> Self:
        return self + rhs.to_A()

@dataclass
class B:
    num: int

    def to_A(self) -> A:
        return A(self.num)

Can someone explain to me why this is the case?

答案1

得分: 1

在你的类A中,你定义了只能添加SelfSelf。你的add_B方法试图添加SelfA

想象一个A的子类A2。现在,add_B将尝试将它使用to_A构建的A对象传递给一个期望A2的方法。这是被禁止的,因为A不是A2的子类。

这意味着根本不可能对A进行子类化。Mypy可能会报告这个问题,因为它不能安全地知道是否有子类,或者是否将来会有A的子类。

修复方法很明显:在__add__中只接受A作为rhs

    ...

    def __add__(self, rhs: 'A') -> Self:
        ...
英文:

In your class A you define that you can only add Self and Self. Your add_B method tries to add Self and A.

Imagine a subclass A2 of A. Now add_B will try to pass the A object it built with to_A into a method that expects an A2. That is forbidden, because A is not a subclass of A2.

That means it is impossible to subclass A at all. Mypy probably reports this because it cannot safely know that there are no subclasses or that there will never be subclasses of A.

The fix is obvious: accept just A for rhs in __add__.

    ...

    def __add__(self, rhs: 'A') -> Self:
        ...

huangapple
  • 本文由 发表于 2023年8月4日 23:11:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76837194.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定