python / python/mypy

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

Open
#18,203 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Run the provided Python reproducer with mypy 1.13 and compare its result with pyright. Trace how operator checking handles a TypeVar bounded by int | A, then add coverage for the shown expression. Done means the expression typechecks without the unsupported-operand error while existing operator diagnostics remain intact.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers, devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.