Spurious type error in `except` branch after an assignment from an `await` that throws
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
Bug Report
If a loop is guarded with an x is not None condition, and the body of the loop contains a try...except that assigns to x, mypy erroneously concludes that x might be None in the except branch.
To Reproduce
(https://mypy-play.net/?mypy=latest&python=3.12&gist=000b86de168d7bca72f3ff58de4121cb)
import asyncio
from collections.abc import Awaitable
from typing import Optional
R = Awaitable[Optional['R']]
async def boom() -> R:
raise ValueError("Boom!")
async def main() -> None:
x: Optional[R] = boom()
y: R
while x is not None:
try:
x = await x
except:
y = x
break
asyncio.run(main())
Expected Behavior
The program is well-typed.
Actual Behavior
main.py:17: error: Incompatible types in assignment (expression has type "R | None", variable has type "R") [assignment]
Found 1 error in 1 file (checked 1 source file)
Your Environment
See Playground details.
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, den Python-Reproducer aus dem verlinkten mypy-play-Beispiel auszuführen, und verfolge, wie die Typ-Eingrenzung über die await-Zuweisung und den except-Zweig hinweg behandelt wird. Das Issue nennt keine Repository-Datei oder keinen Test; abgeschlossen ist die Aufgabe, wenn das Beispiel ohne den gemeldeten Zuweisungsfehler akzeptiert wird und das Verhalten durch Regressionstests abgedeckt ist.
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