python / python/mypy

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

Abierto
#10,380 4 comentarios 1 reacción 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

bug topic-type-narrowing topic-union-types
Lenguaje dominante
Python
Estrellas
20.6k
Forks
3.3k
Métricas de merge de PR
Métricas de PR pendientes

Descripción

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)

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Reproduce los diagnósticos informados ejecutando mypy en test.py y, después, sigue cómo la condición de guardia type(a) != type(b) afecta al estrechamiento para las comparaciones a < b y b < a. Se da por terminado cuando la condición de tipos equivalentes ya no produce los errores str/int informados y el comportamiento está cubierto por una prueba de regresión.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
python
Área
devtools
Tipo de issue
Error
Dificultad
4/5
Tiempo estimado
3-5 días
Estado de actividad
Estancado
Claridad
Bastante claro
Aptitud para principiantes
42/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.