Type narrowing when condition is assigned to a variable
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
Narrowing techniques perform very well when the condition is calculated inside the if condition. When these are made outside, I can understand that mypy cannot guarantee that the narrow will be ok as the boolean value of the condition might be changed before reaching the if statement. However, when the value of this condition is given outside of the if statement but defined as a Final type, the narrow should be working
Minimal code to repdroduce it:
from typing import Optional, Final
def example_func(value: Optional[int] = None):
condition: Final = value is not None
if condition:
reveal_type(value) # Revealed type is "Union[builtins.int, None]"
value = value + 1 # MYPY ERROR
if value is not None:
reveal_type(value) # Revealed type is "builtins.int"
value = value + 1 # MYPY OK
return 0
Expected Behavior
The type of value for the first if statement should be builtins.int, as the condition variable should remain with the same value that was previously assigned to it.
Actual Behavior
Narrowed not performed, and thus the type of value is still inferred as Optional[int]
Your Environment
- Mypy version used: 0.931
- Mypy command-line flags: None
- Mypy configuration options from
mypy.ini(and other config files): None - Python version used: Python 3.8.10
- Operating system and version: Ubuntu 20
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 l’esempio Python minimale con mypy 0.931 e ispeziona i due risultati di reveal_type intorno alla condizione Final. Traccia il comportamento del restringimento dei tipi per le condizioni assegnate a variabili Final; è completato quando il primo reveal_type riporta builtins.int e la somma seguente viene accettata senza indebolire il comportamento esistente per le condizioni dirette.
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
- 45/100