python / python/mypy

Eager narrowing to `Literal` when possible

オープン
#15,434 コメント 2 件 リアクション 4 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

feature topic-literal-types topic-type-narrowing
主要言語
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.

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

リンクされた mypy-play のケースを使って、3 つの letter_v1letter_v2letter_v3 の例を再現し、その後、mypy がローカル変数の型をどのように推論するかを追跡します。意図された narrowing の動作を特定し、これらの例の回帰テストカバレッジを追加します。letter に明示的な型を指定しなくても、注釈付き関数が型チェックを通れば完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
compilers
issue の種類
機能追加
難易度
5/5
見積もり時間
1週間以上
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
35/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。