return value of sorted() cannot be upcast
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
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
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by running python -m mypy foo.py with the reproduction in the issue, then inspect how mypy handles the return types of list() and sorted(). Trace the relevant builtin and generic-list type checking paths; done means the shown sorted(ints) assignment produces no error without requiring the list(sorted(ints)) workaround.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 38/100