Spurious type error in `except` branch after an assignment from an `await` that throws
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
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.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by running the Python reproducer from the linked mypy-play example and trace how type narrowing is handled across the await assignment and except branch. The issue names no repository file or test; done means the example is accepted without the reported assignment error and the behavior has regression coverage.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100