`not isinstance(x, cls)` inside classmethod does not narrow type
オープン
まだ誰も着手していません。
bug
topic-self-types
topic-type-narrowing
- 主要言語
- Python
- スター
- 20.6k
- フォーク
- 3.3k
- PR マージ指標
- PR 指標を取得中
説明
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).
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
mypy 1.19.1 または現在の master で、2 つの縮約された classmethod の例を再現し、その後 Self の isinstance 型ナローイング経路を調査します。assert not isinstance(x, cls) が Self | float を float にナローイングすることを示す回帰テストのカバレッジを追加し、既存の正のナローイング動作を維持します。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- python
- 領域
- compilers
- issue の種類
- バグ
- 難易度
- 3/5
- 見積もり時間
- 1〜2日
- 活発さ
- 静か
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 55/100