python / python/mypy

False negative: potentially unbound instance attribute doesn't trigger `possibly-undefined` error

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

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

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

説明

Bug Report

When enabling the possibly-undefined error code, a potentially undefined instance attribute doesn't trigger the error, while a potentially unbound variable does.

To Reproduce

def test_possibly_undefined(flag: bool):
    if flag:
        a = 1
    print(a)  # error: Name "a" may be undefined  [possibly-undefined]


class Foo:
    def test_possibly_undefined(self, flag: bool):
        if flag:
            self.a = 1
        print(self.a)  # false negative, should also be a possibly-undefined error


try:
    test_possibly_undefined(False)
except Exception as e:
    print(f"{type(e).__name__}: {e}")  # UnboundLocalError: cannot access local variable 'a' where it is not associated with a value

f = Foo()
try:
    f.test_possibly_undefined(False)
except Exception as e:
    print(f"{type(e).__name__}: {e}")  # AttributeError: 'Foo' object has no attribute 'a'

Also available as mypy Playground, but cannot enable enable_error_code = possibly-undefined there.

Expected Behavior

A possible-undefined error should be reported for line 11 as well, e.g.:

test.py:4: error: Name "a" may be undefined  [possibly-undefined]
test.py:11: error: Attribute "a" may be undefined  [possibly-undefined]
Found 2 errors in 1 file (checked 1 source file)

Actual Behavior

No error reported for line 11.

test.py:4: error: Name "a" may be undefined  [possibly-undefined]
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 1.11.2
  • Mypy command-line flags: --enable-error-code=possibly-undefined
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.12.6

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

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

はじめの一歩

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

調査の方向性

まず、mypy 1.11.2 と possibly-undefined エラーコードを使って例を再現し、次に、未定義の可能性があるローカル変数に関する checker のロジックとリグレッションテストを見つけます。ローカル名の扱いをインスタンス属性の扱いと比較し、Foo の例のカバレッジを追加します。mypy が期待される Attribute "a" may be undefined エラーを報告すれば完了です。

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

評価

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

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

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