Incorrect type narrowing when swapping variables after isinstance check
Nessuno ha ancora preso questa issue.
- Lingua principale
- Python
- Stelle
- 20.6k
- Fork
- 3.3k
- Metriche di merge delle PR
- Metriche PR in attesa
Descrizione
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
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Inizia eseguendo la riproduzione minima in Python con mypy e tracciando il restringimento dei tipi per l'assegnazione della tupla dopo i controlli isinstance. Aggiungi un test di regressione che copra lo scambio e verifica che reveal_type(a) sia Sub1 mentre reveal_type(b) sia Sub2.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- tooling
- Tipo di issue
- Bug
- Difficoltà
- 4/5
- Tempo stimato
- 3-5 giorni
- Stato di attività
- Tranquilla
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 52/100