Eager narrowing to `Literal` when possible
まだ誰も着手していません。
- 主要言語
- Python
- スター
- 20.6k
- フォーク
- 3.3k
- PR マージ指標
- PR 指標を取得中
説明
Feature
I often feel I have to put too much effort into informing mypy that some variables can only hold a finite set of values. It would be helpful if mypy was a bit smarter in the way it infers Literal types.
Pitch
Here are some concrete examples:
from typing import Literal
def letter_v1(number: int) -> Literal["a", "b", "c"]:
if number == 1:
letter = "a"
elif number == 2:
letter = "b"
else:
letter = "c"
# Incompatible return value type (got "str", expected "Literal['a', 'b', 'c']") [return-value]
return letter
def letter_v2(number: int) -> Literal["a", "b", "c"]:
letter = "a" if number == 1 else "b" if number == 2 else "c"
# Incompatible return value type (got "str", expected "Literal['a', 'b', 'c']") [return-value]
return letter
def letter_v3(number: int) -> Literal["a", "b", "c"]:
letter = ("a", "b", "c")[number]
# Incompatible return value type (got "str", expected "Literal['a', 'b', 'c']") [return-value]
return letter
See also: https://mypy-play.net/?mypy=1.3.0&python=3.11&flags=strict&gist=bab569e05877621b90f081fc7bdb7d05
Ideally, I think I should get away without having to specify the type of letter in any of the concrete examples here. A human reviewing this code would easily conclude that there is no issue here, yet mypy struggles.
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
リンクされた mypy-play のケースを使って、3 つの letter_v1、letter_v2、letter_v3 の例を再現し、その後、mypy がローカル変数の型をどのように推論するかを追跡します。意図された narrowing の動作を特定し、これらの例の回帰テストカバレッジを追加します。letter に明示的な型を指定しなくても、注釈付き関数が型チェックを通れば完了です。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- python
- 領域
- compilers
- issue の種類
- 機能追加
- 難易度
- 5/5
- 見積もり時間
- 1週間以上
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 35/100