python / python/mypy

False positive: Incompatible types in capture pattern (pattern captures type "Exception", variable has type <deleted>)

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

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

bug topic-error-reporting topic-match-statement
主要言語
Python
スター
20.6k
フォーク
3.3k
PR マージ指標
PR 指標を取得中

説明

Bug Report
When trying to use a match pattern and bind to a variable with the same name as an except ... as bind, mypy starts returning an error.
If I remove the try/except block or don't try to attempt to reassign the variable, the issue goes away.

I've tried to search for other similar issues, but couldn't find much. Hope it's not a duplicate.

To Reproduce

def main() -> None:
    try:
        pass
    except Exception as exc:
        print(exc)

    result = Exception()  # this could for example be the result of `asyncio.gather(..., return_exceptions=True)`
    match result:
        case Exception() as exc:
            print("got exception", exc)
        case _:
            print("got something else", result)


main()

Gist URL: https://gist.github.com/mypy-play/4d9bc9f42141eb6093823efcbc0dafd7
Playground URL: https://mypy-play.net/?mypy=master&python=3.13&gist=4d9bc9f42141eb6093823efcbc0dafd7&flags=allow-redefinition
Tried with various versions of mypy (1.8.0, 1.15.0, master) and Python (3.10, 3.11, 3.13).
Tried with --allow-redefinition and without.

Expected Behavior

No error from mypy, at least when using --allow-redefinition.

Actual Behavior

main.py:9: error: Incompatible types in capture pattern (pattern captures type "Exception", variable has type <deleted>)  [misc]
main.py:10: error: Trying to read deleted variable "exc"  [misc]
Found 2 errors in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 1.8.0, 1.15.0, master
  • Mypy command-line flags: --allow-redefinition
  • Mypy configuration options from mypy.ini (and other config files): N/A
  • Python version used: 3.10, 3.11, 3.13

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

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

はじめの一歩

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

調査の方向性

main.py の再現コードから始め、--allow-redefinition を付けた場合と付けない場合の両方で mypy を実行します。except ... as による束縛と、後続の exc に対する match のキャプチャパターンとの相互作用を追跡します。このケースのリグレッションカバレッジを追加し、再現コードで互換性のないキャプチャまたは削除された変数のエラーが報告されなくなれば完了です。

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

評価

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

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

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