Inference in the `else` block of a try-except-else
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
Bug Report
In the else branch of a try-except-else, mypy ought to be able to infer that no except branch was taken.
To Reproduce
https://mypy-play.net/?mypy=latest&python=3.11&gist=306f5b87e1b2eadc3f7692718a21f6b5
import random
def maybe_int() -> int:
if random.choice([True, False]):
return 42
else:
raise ValueError
def main() -> None:
try:
x = maybe_int()
except ValueError:
x = None
else:
x += 1 # mypy error occurs here
Expected Behavior
At the last line of the example, I expected mypy to infer that the except branch hadn't been taken, and therefore x was of type int, just as it is at the end of the try branch.
Actual Behavior
test.py:17: error: Unsupported operand types for + ("None" and "int") [operator]
test.py:17: note: Left operand is of type "Optional[int]"
Your Environment
- Mypy version used: 0.991 (compiled: yes)
- Mypy command-line flags: none
- Mypy configuration options from
mypy.ini(and other config files): none - Python version used: 3.10.7
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 mit dem verlinkten mypy-play-Reproducer und bestätige den Optional[int]-Fehler im try-except-else-Beispiel. Verfolge, wie mypy die try-, except- und else-Zweige verarbeitet, und füge eine Regressionstestabdeckung hinzu, die zeigt, dass x im else-Zweig als int inferiert wird und der gemeldete Fehler entfernt wird.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- compilers
- Issue-Typ
- Bug
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 35/100