Skip to content

Arithmetic with type variables fails to typecheck ("Unsupported operand types") #18203

@inducer

Description

@inducer

To Reproduce

from typing import Protocol, TypeVar
from typing_extensions import Self

class A(Protocol):
    def __add__(self, other: int | Self) -> Self: ...
    def __radd__(self, other: int | Self) -> Self: ...


AT = TypeVar("AT", bound=int | A)
# OK:
# AT = TypeVar("AT", int, A)


def f(a: AT) -> None:
    a + a

https://mypy-play.net/?mypy=latest&python=3.12&gist=13a490c6b5b075de398e0c84736fd194

Expected Behavior

It's a little weird that there is a lone type variable, but all cases of the operator application should be covered, so IMO this should typecheck OK. pyright agrees:

WARNING: there is a new pyright version available (v1.1.388 -> v1.1.389).
Please install the new version or set PYRIGHT_PYTHON_FORCE_VERSION to `latest`

/home/andreas/tmp/mypy-arith.py
  /home/andreas/tmp/mypy-arith.py:14:10 - warning: TypeVar "AT" appears only once in generic function signature
    Use "int | A" instead (reportInvalidTypeVarUse)
  /home/andreas/tmp/mypy-arith.py:15:5 - warning: Expression value is unused (reportUnusedExpression)
0 errors, 2 warnings, 0 informations

Actual Behavior

mypy-arith.py:15: error: Unsupported operand types for + (likely involving Union)  [operator]

Your Environment

  • Mypy version used: 1.13
  • Mypy command-line flags: None
  • Mypy configuration options from None
  • Python version used: 3.13

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions