`not isinstance(x, cls)` inside classmethod does not narrow type

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

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

評価

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

調査の方向性

mypy 1.19.1 または現在の master で、2 つの縮約された classmethod の例を再現し、その後 Self の isinstance 型ナローイング経路を調査します。assert not isinstance(x, cls)Self | floatfloat にナローイングすることを示す回帰テストのカバレッジを追加し、既存の正のナローイング動作を維持します。

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

説明

bug topic-self-types topic-type-narrowing

Bug Report

Inside a @classmethod, not isinstance(x, cls) does not appear to narrow the type, while isinstance(x, cls) does.

To Reproduce

This is what I wanted to write:

class Foo:
    def __init__(self, x: float) -> None:
        ...
    
    @classmethod
    def from_foo_or_float_cls(cls, x: Self | float) -> Self:
        if isinstance(x, cls):
            return x
        return cls(x)  # error: Argument 1 to "Foo" has incompatible type "Self | float"; expected "float"  [arg-type]

Further reduced:

class Foo:
    @classmethod
    def foo_1(cls, x: Self | float) -> None:
        assert isinstance(x, cls)
        reveal_type(x)  # expected: "Self"; was: "Self`0"; ✅

    @classmethod
    def foo_2(cls, x: Self | float) -> None:
        assert not isinstance(x, cls)
        reveal_type(x)  # expected: "float"; was: "Self`0" | builtins.float"; ❌

Expected Behavior

not isinstance(x, cls) should narrow the type union to remove Self.

Actual Behavior

Self is still part of the type union.

Your Environment

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

Same behavior can be observers on mypy master with Python 3.14 (tested on the playground).

主要言語
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 を短くまとめたダイジェスト。