KEMBAR78
Different overlap checking between `__mul__` and `__rmul__` · Issue #18498 · python/mypy · GitHub
Skip to content

Different overlap checking between __mul__ and __rmul__ #18498

@leamingrad

Description

@leamingrad

Bug Report

When attempting to add overrides to the __mul__ and __rmul__ magic methods, different behaviour is observed for the same set of overrides.

This seems similar to the issue in #10755, but that has since been fixed.

To Reproduce

Playground link: https://mypy-play.net/?mypy=latest&python=3.12&gist=1297febcc3b38a2eea422e7073842c31

(Note that this playground is for the latest version (1.14.1), but the same errors are observed on master)

Sample program:

from typing import TypeVar, overload
from decimal import Decimal

TAmount = TypeVar("TAmount", int, Decimal)


class Unit:
    @overload
    def __mul__(self, other: Unit) -> Unit: ...
    @overload
    def __mul__(self, other: TAmount) -> Quantity[TAmount]: ...

    def __mul__(self, other: Unit | TAmount) -> Unit | Quantity[TAmount]:
        raise NotImplementedError

    @overload
    def __rmul__(self, other: Unit) -> Unit: ...
    @overload
    def __rmul__(self, other: TAmount) -> Quantity[TAmount]: ...

    def __rmul__(self, other: Unit | TAmount) -> Unit | Quantity[TAmount]:
        raise NotImplementedError


class Quantity[TAmount]:
    def __init__(self, value: TAmount, units: Unit) -> None:
        self.value = value
        self.units = units

Expected Behavior

I expect this program to typecheck successfull (or error for both __mul__ and __rmul__)

Actual Behavior

main.py:22: error: Signatures of "__rmul__" of "Unit" and "__mul__" of "Unit | int" are unsafely overlapping  [misc]
main.py:22: error: Signatures of "__rmul__" of "Unit" and "__mul__" of "Unit | Decimal" are unsafely overlapping  [misc]
Found 2 errors in 1 file (checked 1 source file)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions