Optional types not fully narrowed with multiple conditionals
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
Mypy does not fully narrow optional types when multiple conditionals are involved. I suspect this is because it is not able to make an inference step when performing type narrowing. e.g., below, you have facts ~ (x is None and y is None) and x is None on line 6, which allows you to narrow y: int | None to y: int. y: None can't happen, because y is None -> ~ x is None -> contradiction given the above facts.
To Reproduce
def f(x: int | None, y: int | None) -> int:
if x is None and y is None:
return 0
if x is None:
# y guaranteed non-null
reveal_type(y) # int | None, but should be int
return y + 1
Expected Behavior
mypy should narrow y to int.
Actual Behavior
mypy is not able to narrow y from int | None, and gives a false positive error:
sandbox.py:5: note: Revealed type is "Union[builtins.int, None]"
sandbox.py:6: error: Unsupported operand types for + ("None" and "int") [operator]
sandbox.py:6: note: Left operand is of type "int | None"
Your Environment
- Mypy version used: 1.7.0
- Mypy command-line flags: none
- Mypy configuration options from
mypy.ini(and other config files): none - Python version used: 3.12.0
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
Riproduci l’esempio in sandbox.py con mypy 1.7.0, Python 3.12 e senza flag di configurazione, quindi traccia il comportamento del restringimento dei tipi per i condizionali multipli. Il lavoro è completato quando y viene rivelato come int e il return passa senza l’errore di operando non supportato segnalato.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- compilers, devtools
- Tipo di issue
- Bug
- Difficoltà
- 4/5
- Tempo stimato
- 3-5 giorni
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 35/100