Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Spurious type error in except branch after an assignment from an await that throws #18074

Open
bcmills opened this issue Oct 30, 2024 · 0 comments
Labels
bug mypy got something wrong

Comments

@bcmills
Copy link

bcmills commented Oct 30, 2024

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.

@bcmills bcmills added the bug mypy got something wrong label Oct 30, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong
Projects
None yet
Development

No branches or pull requests

1 participant