Type narrowing of `target: type[T]` using insinstance seems to fool mypy

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

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

評価

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

調査の方向性

まず、提供された再現プログラムを mypy 1.19.1 で実行し、表示された型と診断結果を期待される動作と比較します。isinstance(target_type, int) と target_type is int に対する型の絞り込みの経路を追跡します。最初の無効な関数が拒否され、サポートされている絞り込み動作が回帰テストでカバーされれば完了です。

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

説明

bug topic-type-narrowing

Bug Report
Well, I was writing some sort of converter from unstructured data to a dataclass, so I had a function that uses f[T](obj, target_type: type[T]) -> T and while in the end I stick to typing.cast for that, I also tried several solutions, they are below.

One of them intuitively should(?) work (return_checktype), but mypy refuses to follow them, and one of them is obviously wrong in hindsight (return_checkval), but mypy is happy with it.

To Reproduce

from typing import reveal_type


def return_checkval[T](target_type: type[T]) -> T:
    # runtime check that target_type is int
    if isinstance(target_type, int):
        reveal_type(target_type)
        return 42  # and they lived happily ever after

    raise ValueError("Unsupported type")


x = return_checkval(int)
print(x)


def return_checktype[T](target_type: type[T]) -> T:
    # runtime check that target_type is int
    if target_type is int:
        reveal_type(target_type)
        return 42  # errors here

    raise ValueError("Unsupported type")


# example test
x = return_checktype(int)
print(x)

Expected Behavior

At the very least, it should have two reveal_type outputs, and it should reject the first function completely. That's what (based)pyright.
Ideally, it should also allow the second function, but (based)pyright also rejects it :(

Actual Behavior

t.py:20: note: Revealed type is "type[T`-1]"
t.py:21: error: Incompatible return value type (got "int", expected "T")  [return-value]
Found 1 error in 1 file (checked 1 source file)
Traceback (most recent call last):
  File "/private/tmp/test/t.py", line 13, in <module>
    x = return_checkval(int)
  File "/private/tmp/test/t.py", line 10, in return_checkval
    raise ValueError("Unsupported type")
ValueError: Unsupported type

Your Environment

mypy version 1.19.1 (compiled yes)
python version .. honestly have no idea which one it uses, but python --version is 3.14
just run it mypy . from the folder in /tmp

主要言語
Python
スター
20.6k
フォーク
3.3k
平均マージ
1日 18時間
マージ済み PR(30日)
54

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

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

はじめの一歩

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

python/mypy のほかの issue

python/mypy の issue をすべて見る

似ている issue

Python の issue をもっと見る

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

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