python / python/mypy

`TypeGuard` has no effect when nested in the presence of other problems

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

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

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

説明

Bug Report

A TypeGuard declared and used near the top of a function is sometimes rendered ineffective (i.e., there is no change to the type of the first argument to the TypeGuard even when the TypeGuard returns True), but only when there is an apparently-unrelated mypy-detectable problem later in the same function.

The problem does not occur if the TypeGuard definition is not nested within an outer function, or if the apparently-unrelated problem is corrected.

Because any erroneous errors triggered by this bug appear above the triggering problem in the error report, users will find it difficult to solve this issue if they approach the problem using a [run mypy, fix first issue, repeat] workflow.

To Reproduce

[mypy-play.net]

from __future__ import annotations
from typing_extensions import (
        TypeGuard,
        assert_type,
        )

def some_func(arg: object) -> None:
    '''must encapsulate the following in a func, or issue won't repro
    '''
    def tg_int(arg: object) -> TypeGuard[int]:
        '''must be nested: issue won't repro if decl'd at module scope'''
        b: bool
        return b

    # replacing 'arg' with a local var works just as well
    if tg_int(arg):                                                     # line 16
        assert_type(arg, int)                                           # line 17
                # expected: no error
                # got: [assert-type]
                #   "Expression is of type 'object', not 'int'"

    # this is wrong, but removing it causes the unexpected error to
    # vanish:
    var1 = non_existant_var  # type: ignore[name-defined]

Expected Behavior

The TypeGuard invocation at line 16 should change the type of arg to int when the if statement's condition is truthy. The assert_type() on line 17 should pass.

Actual Behavior

The TypeGuard has no effect on the type of its argument.

Your Environment

  • Mypy version used: 1.9.0, master (as provided by mypy-play.net as of 2024-04-17)
  • Mypy command-line flags: (none necessary)
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.8, 3.12

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

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

はじめの一歩

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

調査の方向性

リンクされた mypy-play.net の再現コードから始め、mypy 1.9.0 または master に対して実行します。後続の name-defined エラーが存在する場合に、ネストされた TypeGuard が arg を絞り込まない理由を調査します。完了の条件は、assert_type(arg, int) のチェックが通り、後続のエラーが引き続き無視されることです。

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

評価

技術スタック
python
領域
compilers
issue の種類
バグ
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
明確に書かれている
初心者へのやさしさ
45/100

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

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