return value of sorted() cannot be upcast
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
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
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginne damit, python -m mypy foo.py mit der Reproduktion aus dem Issue auszuführen, und untersuche dann, wie mypy die Rückgabetypen von list() und sorted() behandelt. Verfolge die relevanten Pfade für die Typprüfung von Builtins und generischen Listen; abgeschlossen ist die Aufgabe, wenn die gezeigte Zuweisung sorted(ints) keinen Fehler erzeugt, ohne den Workaround list(sorted(ints)) zu benötigen.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- devtools
- Issue-Typ
- Bug
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 38/100