python / python/mypy

`TypeIs` with `isinstance` fails to narrow

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

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

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

説明

Bug Report

If I use TypeIs along with isinstance, the type doesn't get narrowed

To Reproduce

from typing import TypeIs, Any, TypeAlias, reveal_type

SliceInt: TypeAlias = slice[int | None, int | None, int | None]
SliceStr: TypeAlias = slice[str | None, str | None, str | None]


def is_slice_int(obj: Any) -> TypeIs[SliceInt]:  # type: ignore[empty-body]
    ...



def main(obj: SliceInt | SliceStr) -> None:
    if is_slice_int(obj):
        pass
    elif isinstance(obj, slice):
        reveal_type(obj)

https://mypy-play.net/?mypy=latest&python=3.14&gist=170b0c83ef93742ff998485be01e9440

Expected Behavior

t.py:19: note: Revealed type is "slice[str | None, str | None, str | None]"

Actual Behavior

t.py:19: note: Revealed type is "slice[int | None, int | None, int | None] | slice[str | None, str | None, str | None]"

Note that, for comparison, pyright and pyrefly get this right:

(scratch) mgorelli@marcoslaptop:~/scratch$ pyright t.py
pyre/home/mgorelli/scratch/t.py
  /home/mgorelli/scratch/t.py:19:21 - information: Type of "obj" is "slice[str | None, str | None, str | None]"
0 errors, 0 warnings, 1 information
(scratch) mgorelli@marcoslaptop:~/scratch$ pyright t.py
/home/mgorelli/scratch/t.py
  /home/mgorelli/scratch/t.py:19:21 - information: Type of "obj" is "slice[str | None, str | None, str | None]"
0 errors, 0 warnings, 1 information
(scratch) mgorelli@marcoslaptop:~/scratch$ pyrefly check t.py
 INFO revealed type: slice[str | None, str | None, str | None] [reveal-type]
  --> t.py:19:20
   |
19 |         reveal_type(obj)
   |                    -----
   |
 INFO 0 errors

Your Environment

  • Mypy version used: 2.1.0
  • Mypy command-line flags:
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: 3.13.13

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

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

はじめの一歩

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

調査の方向性

リンクされた mypy-play の再現例から始め、TypeIs/isinstance 分岐で明らかになる型を期待される出力と比較します。TypeIsisinstance の型の絞り込みへのエントリポイントを追跡し、次にその例で明らかになるのが SliceStr だけであることを確認し、該当するテスト箇所が見つかった場合はこのリグレッションのカバレッジを追加します。

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

評価

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

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

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