python / python/mypy

return value of sorted() cannot be upcast

Open
#17,296 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-type-context
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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.