Thomas
Thomas

Reputation: 715

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

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?

Upvotes: 0

Views: 124

Answers (1)

Wombatz
Wombatz

Reputation: 5458

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:
        ...

Upvotes: 1

Related Questions