python / python/mypy

[2.0 regression] Bad result from heuristic non-narrowing of type[T]

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

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

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

説明

Bug Report

(A clear and concise description of what the bug is.)

To Reproduce

from math import isnan
from typing import TypeVar

V = TypeVar("V")


def assert_scalar_equal(s1: V, s2: V, /) -> None:
    assert type(s1) is type(s2)
    if type(s1) is float and type(s2) is float and isnan(s2):
        assert isnan(s1)
    else:
        assert s1 == s2

Expected Behavior

This snippet should type check.

Actual Behavior

mypy.ini: No [mypy] section in config file
t.py:9: error: Argument 1 to "isnan" has incompatible type "V"; expected "SupportsFloat | SupportsIndex"  [arg-type]
t.py:10: error: Argument 1 to "isnan" has incompatible type "V"; expected "SupportsFloat | SupportsIndex"  [arg-type]
Found 2 errors in 1 file (checked 1 source file)

Even more minimal reprod:

from math import isnan
from typing import TypeVar

V = TypeVar("V")


def foo(s1: V, /) -> None:
    if type(s1) is float:
        assert isnan(s1)
mypy.ini: No [mypy] section in config file
t.py:9: error: Argument 1 to "isnan" has incompatible type "V"; expected "SupportsFloat | SupportsIndex"  [arg-type]
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 2.0.0 or 2.1.0
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: tested 3.11.14 and 3.14.6

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

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

はじめの一歩

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

調査の方向性

まず、mypy 2.0.0 または 2.1.0 で最小限の t.py 再現コードを実行し、type(s1) is float の後の型の絞り込みの挙動を確認してください。isnan に対して期待される絞り込みと比較してください。完了条件は、提示された両方のスニペットが報告された arg-type エラーなしで型チェックを通ることです。

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

評価

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

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

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