python / python/mypy

MyPy fails on Union[str, int] < Union[str, int] when underlying type is known

Aperta
#10,380 4 commenti 1 reazione 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

bug topic-type-narrowing topic-union-types
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

Bug Report

Given the following script I'm receiving several unexpected errors:

test.py:22: error: Unsupported operand types for < ("str" and "int")
test.py:22: error: Unsupported operand types for < ("int" and "str")
test.py:22: note: Both left and right operands are unions
test.py:24: error: Unsupported operand types for < ("str" and "int")
test.py:24: error: Unsupported operand types for < ("int" and "str")
test.py:24: note: Both left and right operands are unions
Found 4 errors in 1 file (checked 1 source file)

Even though the if-block and assert statement just before the comparison operator usage on a and b clearly filters out the case of mismatching types. I've only added the assert statement in the hope of telling mypy that these variables have the same type, but no luck there.

from typing import Union

def semver_prerelease_compare(lhs: str, rhs: str) -> bool:
    a: Union[str, int]
    b: Union[str, int]
    for a, b in zip(lhs.split("."), rhs.split(".")):
        try:
            a = int(a)
        except ValueError:
            pass
        try:
            b = int(b)
        except ValueError:
            pass

        if isinstance(a, int) and not isinstance(b, int):
            # Numeric identifiers sort before non-numeric ones
            return True
        if type(a) != type(b):
            return False
        if a < b:
            return True
        elif b < a:
            return False

    return len(lhs) < len(rhs)

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

Riproduci le diagnostiche segnalate eseguendo mypy su test.py, quindi traccia il modo in cui la condizione di guardia type(a) != type(b) influisce sul restringimento per i confronti a < b e b < a. Il lavoro è completato quando la condizione per tipi equivalenti non produce più gli errori str/int segnalati e il comportamento è coperto da un test di regressione.

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
42/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.