Can't assign result of list addition to list variable covariantly
まだ誰も着手していません。
- 主要言語
- Python
- スター
- 20.6k
- フォーク
- 3.3k
- PR マージ指標
- PR 指標を取得中
説明
Bug Report
I cannot assign a list[int] to a list[int | None] if I make it using addition. However, it works fine if I don't use addition. See the tiny example below.
In this example, of course, I can avoid the problem using the list literal [1, 2], but in the application code where I'm facing this issue I actually need to add two comprehensions and store the result as a variable. It shows the same unexpected behavior.
To Reproduce
a: list[int | None] = [1] # allowed
b: list[int | None] = [1] + [2] # not allowed
https://mypy-play.net/?mypy=latest&python=3.12&gist=800cfe12c8689a108440e71e641ad240
Expected Behavior
I expect mypy to behave in one of two ways:
- Both lines are allowed 👈 this would be very convenient
- Both lines are not allowed 👈 this would be correct
- How can the first line be allowed if
listis invariant? - In this case I would need a way to type-hint a list comprehension
- How can the first line be allowed if
Note:
I expect both lines to be treated the same way. This expectation is reinforced because reveal_type([1]) reports the same type as reveal_type([1] + [2]). If that was not the case the different treatment would be easier to understand.
Actual Behavior
main.py:2: error: Incompatible types in assignment (expression has type "list[int]", variable has type "list[int | None]") [assignment]
main.py:2: note: "List" is invariant -- see https://mypy.readthedocs.io/en/stable/common_issues.html#variance
main.py:2: note: Consider using "Sequence" instead, which is covarian
Your Environment
- Mypy version used:
1.8.0and1.5.1(latest and version in use on my project) - Mypy command-line flags:
none - Mypy configuration options from
mypy.ini(and other config files):none - Python version used:
3.12
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
main.py の最小再現から始め、報告されている Python と mypy のバージョンを使って、リンク先の mypy-play の例に対して実行します。リストリテラルとリスト加算の式がどのように推論されるかを追跡し、そのうえでリストの不変性を維持しながら、それらの代入動作を一貫させます。両方の形式について回帰テストを追加または更新します。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- python
- 領域
- devtools
- issue の種類
- バグ
- 難易度
- 4/5
- 見積もり時間
- 3〜5日
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 35/100