python / python/mypy

Argument "key" to "sorted" has incompatible type "Callable…"

Abierto
#19,259 1 comentario 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

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

Descripción

Bug Report

I believe that I've found a bug in mypy, the following MRE should as far as I can tell not result in any typing errors at all, but it reports an error (and I've found two simple workarounds for which no error is reported, strengthening my belief that this is a bug and not intended behaviour).

To Reproduce

#!/usr/bin/python3

from collections.abc import Iterable
from typing import cast


def unproblematic(iter: Iterable[int]) -> None:
    print(iter)


def problematic(iter: Iterable[int | str]) -> None:
    print(iter)


def key(item: int) -> int:
    return -item


def main() -> None:
    items: list[int] = [3, 4, 1, 2]

    unproblematic(sorted(items, key=key))  # Works.
    problematic(sorted(items, key=key))  # Fails mypy arg-type.

    workaround = sorted(items, key=key)
    problematic(workaround)  # Works.

    problematic(cast(Iterable[int], sorted(items, key=key)))  # Works.


if __name__ == '__main__':
    main()

Actual Behavior

$ mypy mre.py
mre.py:23: error: Argument "key" to "sorted" has incompatible type "Callable[[int], int]"; expected "Callable[[int | str], SupportsDunderLT[Any] | SupportsDunderGT[Any]]"  [arg-type]

Your Environment

$ mypy --version                
mypy 1.16.0 (compiled: yes)
$ python3 --version
Python 3.13.3

(If anyone can't trivially reproduce this, I'd be happy to provide more details about my environment.)

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

Empieza reproduciendo el informe del MRE en mre.py con mypy 1.16.0 y Python 3.13.3; después, compara la llamada directa sorted(items, key=key) con las dos soluciones alternativas. Se considera terminado cuando la llamada directa ya no informe del argumento key incompatible y el ejemplo siga estando correctamente tipado.

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
Bien especificado
Aptitud para principiantes
35/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.