return value of sorted() cannot be upcast
まだ誰も着手していません。
- 主要言語
- Python
- スター
- 20.6k
- フォーク
- 3.3k
- PR マージ指標
- PR 指標を取得中
説明
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
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
まず、issue にある再現例で python -m mypy foo.py を実行し、次に mypy が list() と sorted() の戻り値の型をどのように扱うかを調べます。組み込み型とジェネリックリストの型チェックに関係する経路を追跡します。完了条件は、list(sorted(ints)) の回避策を必要とせず、示されている sorted(ints) の代入でエラーが発生しないことです。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- python
- 領域
- devtools
- issue の種類
- バグ
- 難易度
- 4/5
- 見積もり時間
- 3〜5日
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 38/100