python / python/mypy

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

Offen
#19,454 1 Kommentar 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

bug
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

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

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Beginne mit der mypy-play-Reproduktion und dem entsprechenden test3.py-Snippet unter mypy 1.17.0 und vergleiche dann dessen TypeVar-Narrowing mit der Version mit direkter Union. Verfolge den Type-Checking-Pfad für das isinstance-Narrowing und Vergleichsoperatoren. Als erledigt gilt es, wenn das generische Beispiel keinen Fehler erzeugt, während Vergleiche zwischen gemischten Typen weiterhin abgelehnt werden.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
devtools
Issue-Typ
Bug
Schwierigkeit
4/5
Geschätzter Aufwand
3-5 Tage
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
48/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.