python / python/mypy

Missing `TypeIs` narrowing for variadic tuples

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

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

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

説明

I noticed this behavior when investigating a similar issue in pyright.

Mypy isn't correctly narrowing tuples in some cases.

from typing_extensions import TypeIs


def is_tuple_of_strings(v: tuple[int | str, ...]) -> TypeIs[tuple[str, ...]]:
    return all(isinstance(x, str) for x in v)


def test1(t: tuple[int]) -> None:
    if is_tuple_of_strings(t):
        reveal_type(t)  # Should be Never ✅ 
    else:
        reveal_type(t)  # Should be tuple[int] ✅ 

def test2(t: tuple[str, int]) -> None:
    if is_tuple_of_strings(t):
        reveal_type(t)  # Should be Never ✅ 
    else:
        reveal_type(t)  # Should be tuple[str, int] ✅ 

def test3(t: tuple[int | str]) -> None:
    if is_tuple_of_strings(t):
        reveal_type(t)  # Should be tuple[str] ✅ 
    else:
        reveal_type(t)  # Should be tuple[int] or tuple[int | str] ❌ (mypy: Never)

def test4(t: tuple[int | str, int | str]) -> None:
    if is_tuple_of_strings(t):
        reveal_type(t)  # Should be tuple[str, str] ✅ 
    else:
        reveal_type(t)  # Should be tuple[int | str, int | str] or tuple[int, int | str] | tuple[str, int] ❌ (mypy: Never)

def test5(t: tuple[int | str, ...]) -> None:
    if is_tuple_of_strings(t):
        reveal_type(t)  # Should be tuple[str, ...] ✅ 
    else:
        reveal_type(t)  # Should be tuple[int | str, ...] ❌ (mypy: Never)

def test6(t: tuple[str, *tuple[int | str, ...], str]) -> None:
    if is_tuple_of_strings(t):
        reveal_type(t)  # Should be tuple[str, *tuple[str, ...], str] ❌ (mypy: tuple[str, Never, str])
    else:
        reveal_type(t)  # Should be tuple[str, *tuple[int | str, ...], str] ❌ (mypy: Never)

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

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

はじめの一歩

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

調査の方向性

まず、mypy を使って 6 つの例を再現し、それぞれの reveal_type の結果を issue で期待されている型の絞り込みと比較します。次に、TypeIs と可変長タプルの型の絞り込みの実装を追跡し、その後、これらのケースのリグレッションテストを追加します。reveal された型が期待される結果と一致し、リグレッションがなければ完了です。

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

評価

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

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

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