python / python/mypy

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

Aperta
#19,259 1 commento 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

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

Descrizione

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.)

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 riproducendo il report dall’MRE in mre.py con mypy 1.16.0 e Python 3.13.3, quindi confronta la chiamata diretta sorted(items, key=key) con le due soluzioni alternative. Il lavoro è completato quando la chiamata diretta non segnala più l’argomento key incompatibile e l’esempio rimane tipizzato correttamente.

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
Specificata chiaramente
Idoneità per principianti
35/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.