python / python/mypy

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

オープン
#18,074 コメント 1 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

bug topic-type-narrowing
主要言語
Python
スター
20.6k
フォーク
3.3k
平均マージ
1日 18時間
マージ済み PR(30日)
54

説明

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.

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

まず、リンクされた mypy-play の例から Python reproducer を実行し、await での代入と except 分岐にまたがって型の絞り込みがどのように扱われるかを追跡します。Issue ではリポジトリ内のファイルもテストも指定されていません。完了条件は、報告された代入エラーなしで例が受け入れられ、その挙動に回帰テストのカバレッジがあることです。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
compilers
issue の種類
バグ
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
35/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。