python / python/mypy

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

Open
#18,074 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-type-narrowing
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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.