Incorrect type narrowing when swapping variables after isinstance check
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
Bug Report
Swapping the variables doesn't seem to make mypy swap their types and the second variable is left with its type as before the swap.
Changing the example below to use a temp variable fixes the issue:
tmp = a
a, b = b, tmp
reveal_type(a) # note: Revealed type is "test.Sub1"
reveal_type(b) # note: Revealed type is "test.Sub2"
To Reproduce
class Base:
pass
class Sub1(Base):
pass
class Sub2(Base):
pass
def f(a: Base, b: Base) -> None:
if isinstance(b, Sub1) and isinstance(a, Sub2):
a, b = b, a
reveal_type(a) # note: Revealed type is "test.Sub1"
reveal_type(b) # note: Revealed type is "test.Sub1"
Expected Behavior
Type of b is Sub2 after the swap.
Actual Behavior
Type of b is Sub1 after the swap.
Your Environment
- Mypy version used: mypy 2.2.0+dev.52de0c739d2f066ea06fa9a886bc8fcc9fa079c6
- Mypy command-line flags: None
- Mypy configuration options from
mypy.ini(and other config files): None - Python version used: 3.13.5
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
Beginne damit, die minimale Python-Reproduktion mit mypy auszuführen und die Typverengung für die Tupelzuweisung nach den isinstance-Prüfungen nachzuverfolgen. Füge einen Regressionstest hinzu, der den Tausch abdeckt, und überprüfe, dass reveal_type(a) Sub1 und reveal_type(b) Sub2 ist.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- tooling
- Issue-Typ
- Bug
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Ruhig
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 52/100