Type narrowing when condition is assigned to a variable
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
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
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, das minimale Python-Beispiel mit mypy 0.931 auszuführen, und untersuche die beiden reveal_type-Ergebnisse rund um die Final-Bedingung. Verfolge das Verhalten der Typverengung für Bedingungen, die Final-Variablen zugewiesen sind; abgeschlossen ist die Aufgabe, wenn das erste reveal_type builtins.int meldet und die folgende Addition akzeptiert wird, ohne das bestehende Verhalten für direkte Bedingungen abzuschwächen.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- compilers, devtools
- Issue-Typ
- Bug
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 45/100