python / python/mypy

Comparison operators emit "Unsupported operand types" when using `isinstance` to narrow `TypeVar` to union of numeric types

Aperta
#19,454 1 commento 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

Bug Report

I have a generic class that wraps a bool, float, int, or str. It implements the comparison operator magic methods like __lt__ etc., using isinstance to ensure that callers don't mix bool/float/int with str. With mypy 1.16.1, this does not error, but with mypy 1.17.0, the comparison operators started emitting "error: Unsupported operand types for < (likely involving Union) [operator]"

To Reproduce

Minimal reproduction (using a generic function instead of a generic class): https://mypy-play.net/?mypy=latest&python=3.12&gist=dd4696c3ba71103c49d7a4aaf34b2aef

def f[T: float | int | str](x: T, y: T) -> bool:
    if isinstance(x, (float, int)) and isinstance(y, (float, int)):
        return x < y
    elif isinstance(x, str) and isinstance(y, str):
        return x < y
    else:
        raise TypeError

Expected Behavior

No errors.

Actual Behavior

test3.py:3: error: Unsupported operand types for < (likely involving Union)  [operator]
Found 1 error in 1 file (checked 1 source file)

It does not error if I remove the type variable and use union types directly:
def f(x: float | int | str, y: float | int | str) -> bool:

Your Environment

  • Mypy version used: 1.17.0
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.12.9

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

Inizia con la riproduzione in mypy-play e lo snippet equivalente di test3.py con mypy 1.17.0, quindi confronta il relativo narrowing di TypeVar con la versione con unione diretta. Traccia il percorso del controllo dei tipi per il narrowing di isinstance e gli operatori di confronto. Il lavoro è completato quando l’esempio generico non produce errori, mentre i confronti tra tipi misti continuano a essere rifiutati.

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

Valutazione

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

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.