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

Offen
#21,271 0 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

Bewertung

Schwierigkeit
3/5
Geschätzter Aufwand
1-2 Tage
Anfängerfreundlichkeit
55/100
Issue-Typ
Bug
Klarheit
Größtenteils klar
Aktivitätsstatus
Ruhig
Tech-Stack
python
Bereich
compilers

Rechercherichtung

Reproduziere die beiden reduzierten classmethod-Beispiele mit mypy 1.19.1 oder dem aktuellen master und untersuche anschließend den isinstance-Typ-Narrowing-Pfad für Self. Füge eine Regressionstestabdeckung hinzu, die zeigt, dass assert not isinstance(x, cls) Self | float auf float einschränkt, während das bestehende positive Narrowing-Verhalten erhalten bleibt.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Beschreibung

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).

Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
Ø Merge
1 T. 18 Std.
Gemergte PRs (30 T.)
54

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lesen Sie das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreiben Sie ins Issue, dass Sie es übernehmen — das erspart doppelte Arbeit.
  3. Forken Sie das Repository und arbeiten Sie in einem Branch.
  4. Öffnen Sie einen Pull Request, der die Issue-Nummer nennt.

Mehr aus python/mypy

Alle Issues in python/mypy

Ähnliche Issues

Weitere Issues zu Python

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.