python / python/mypy

TypeGuard does not narrow when assignment expression

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

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

bug topic-pep-572 topic-typeguard-typeis
主要言語
Python
スター
20.6k
フォーク
3.3k
PR マージ指標
PR 指標を取得中

説明

Bug Report

In the example below, is_str is a type guard, but when used mypy fails to narrow the type. I'm pretty sure this happens because of the assignment expression.

To Reproduce
https://mypy-play.net/?mypy=latest&python=3.12&gist=42da00a72ace0a51a5d2335721877591

import typing

s: str | int


def is_str(x: str | int) -> typing.TypeGuard[str]:
    return bool(
        isinstance(x, str)
        and (y if len(y := '123'.split('/')) > 1 else '')
    )


if is_str(s):
    s + ''

Expected Behavior
No mypy errors.

Actual Behavior

main.py:14: error: Unsupported operand types for + ("int" and "str") [operator]
main.py:14: note: Left operand is of type "str | int"
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 1.19
  • Mypy command-line flags: non
  • Mypy configuration options from mypy.ini (and other config files): non
  • Python version used: 3.12

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

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

はじめの一歩

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

調査の方向性

mypy-play の再現コードから始め、guard に代入式が含まれている場合に TypeGuard 呼び出しがどのように解析されるかを調べます。main.py が報告する行を期待される narrowing の確認箇所として使用します。サポートされていないオペランドのエラーがなくなり、既存の再現コードがパスすれば完了です。

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

評価

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

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

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