python / python/mypy

(🐞) `overload`s that exhaust finite `Literal`s(`bool`/`Enum`) not treated as exhaustive

オープン
#14,764 コメント 14 件 リアクション 30 件 担当者 0 名 GitHub で見る

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

bug topic-literal-types topic-overloads
主要言語
Python
スター
20.6k
フォーク
3.3k
PR マージ指標
PR 指標を取得中

説明

@overload
def foo(a: Literal[True]) -> int: ...

@overload
def foo(a: Literal[False]) -> str: ...

def foo(a: bool) -> object: ...

a: bool
reveal_type(foo(a))  # error: No overload variant of "foo" matches argument type "bool"
@overload
def foo(a: Literal[True]) -> int: ...

@overload
def foo(a: Literal[False]) -> str: ...

@overload
def foo(a: bool) -> object: ...  # no error regarding impossible to match overload

a: bool
reveal_type(foo(a))  # object
@overload
def foo(a: Literal[True, False]) -> int | str: ...

@overload
def foo(a: bool) -> object: ...  # error: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader

def foo(a: bool) -> object: ...

a: bool
reveal_type(foo(a))  # int | str

Here mypy incorrectly forces us to implement a completely redundant overload for the non Literal case when it is already exhaustively covered by both literals. It is only when the literals are in the same overload (useless in practice, but just for demonstration) that mypy correctly handles this case.

Mypy should be doing 'union math' (or what ever it's called) to apply both literal overloads at once.

This also affects all other exhaustible Literals such as Enums.

This example is pulled directly from the docs, so I think they should be updated as well to an example that doesn't contain this confusing defect.

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

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

はじめの一歩

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

調査の方向性

まず issue にある overload の例を再現し、リンクされた Literal types のドキュメントを読んでください。mypy による overload のマッチングと、有限個の Literal および Enum の値の扱いを追跡してください。すべてのケースを網羅する個別の Literal overload が、冗長な非 Literal overload をもはや必要とせず、影響を受けるドキュメント例が更新されれば完了です。

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

評価

技術スタック
python
領域
devtools
issue の種類
バグ
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
38/100

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

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