return value of sorted() cannot be upcast
Nessuno ha ancora preso questa issue.
- Lingua principale
- Python
- Stelle
- 20.6k
- Fork
- 3.3k
- Metriche di merge delle PR
- Metriche PR in attesa
Descrizione
Bug Report
Mypy allows the return value of list() to be upcasted. eg. list[int] -> list[object] (or list[int | None]). Mypy does not permit the same behaviour with the return value of sorted(). Like list(), sorted() is a builtin, creates a new list, and does not retain a reference to the returned value. Mypy should allow the return value of sorted() to be upcast, because it is safe to do so.
To Reproduce
# file: foo.py
ints: list[int] = [1,2,3]
objects: list[object] = sorted(ints) # error!
Command line:
python -m mypy foo.py
Expected Behavior
That no error should be reported, much like if list() were used instead of sorted(). ie:
ints: list[int] = [1, 2, 3]
objects: list[object] = list(ints)
# undesirable work around
objects2: list[object] = list(sorted(ints))
Actual Behavior
foo.py:11: error: Incompatible types in assignment (expression has type "list[int]", variable has type "list[object]") [assignment]
foo.py:11: note: "List" is invariant -- see https://mypy.readthedocs.io/en/stable/common_issues.html#variance
foo.py:11: note: Consider using "Sequence" instead, which is covariant
Found 1 error in 1 file (checked 1 source file)
Your Environment
- Mypy version used: 1.10.0
- Mypy command-line flags: none
- Mypy configuration options from
mypy.ini(and other config files): none - Python version used: 3.12.0
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Inizia eseguendo python -m mypy foo.py con la riproduzione nell’issue, quindi esamina come mypy gestisce i tipi restituiti da list() e sorted(). Segui i percorsi rilevanti per il controllo dei tipi dei builtin e delle liste generiche; il lavoro è completato quando l’assegnazione mostrata sorted(ints) non produce errori senza richiedere il workaround list(sorted(ints)).
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
- 38/100