`not isinstance(x, cls)` inside classmethod does not narrow type
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
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).
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
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.
Bewertung
- Tech-Stack
- python
- Bereich
- compilers
- Issue-Typ
- Bug
- Schwierigkeit
- 3/5
- Geschätzter Aufwand
- 1-2 Tage
- Aktivitätsstatus
- Ruhig
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 55/100