List[Literal[...]] type being narrowed where it shouldn't be
オープン
まだ誰も着手していません。
bug
topic-literal-types
topic-type-narrowing
- 主要言語
- Python
- スター
- 20.6k
- フォーク
- 3.3k
- PR マージ指標
- PR 指標を取得中
説明
Bug Report
Adding an if check on a specific index of a List of Literals seems to narrow down its scope, even though the list can be modified and the value at that index can change.
To Reproduce
Run mypy over this piece of code:
foo: List[Literal['a', 'b']] = ['a', 'b', 'a']
if foo[0] == 'a':
print('a')
exit()
foo.pop(0)
reveal_type(foo[0])
if foo[0] == 'a':
pass
Expected Behavior
Revealed type to be Literal['a', 'b'], and the conditional to be valid.
Actual Behavior
t.py:11: note: Revealed type is 'Literal['b']'
t.py:12: error: Non-overlapping equality check (left operand type: "Literal['b']", right operand type: "Literal['a']")
Your Environment
- Mypy version used: 0.790
- Mypy command-line flags:
--strict - Python version used: 3.9.1 64-bit
- Operating system and version: Fedora 33 x86_64
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
まず、提供されている Python 再現コードを mypy 0.790 で実行し、インデックス付きの可変 Lists に含まれる Literals の型絞り込みの挙動を調べます。foo[0] の絞り込みのエントリポイントを checker 内で追跡します。完了条件は、pop(0) の後も reveal_type(foo[0]) が Literal['a', 'b'] のままであり、後続の等価性チェックが受け入れられることです。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- python
- 領域
- devtools
- issue の種類
- バグ
- 難易度
- 4/5
- 見積もり時間
- 3〜5日
- 活発さ
- 停滞
- 明瞭さ
- 明確に書かれている
- 初心者へのやさしさ
- 42/100