python / python/mypy

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

Aperta
#18,203 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

bug
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

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

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Esegui il riproduttore Python fornito con mypy 1.13 e confronta il risultato con pyright. Traccia come il controllo degli operatori gestisce un TypeVar vincolato da int | A, quindi aggiungi la coverage per l’espressione mostrata. Il lavoro è completato quando l’espressione supera il controllo dei tipi senza l’errore unsupported-operand e le diagnostiche degli operatori esistenti rimangono invariate.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
python
Ambito
compilers, devtools
Tipo di issue
Bug
Difficoltà
4/5
Tempo stimato
3-5 giorni
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
35/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.