a nonlocal in class nested within a function causes the referenced var to disappear from the outer scope
オープン
まだ誰も着手していません。
bug
- 主要言語
- Python
- スター
- 20.6k
- フォーク
- 3.3k
- PR マージ指標
- PR 指標を取得中
説明
Bug Report
c.f.: #12730
When a class definition appears within a function, a nonlocal in the class body causes the referenced variable to disappear from the outer scope.
To Reproduce
Analyze: [mypy-play.net]
from __future__ import annotations
from typing import (
Optional,
)
from typing_extensions import (
assert_type,
)
def in_a_function() -> None:
some_value: Optional[int] = None
assert_type(some_value, Optional[int])
class SomeClass:
nonlocal some_value
assert_type(some_value, Optional[int])
some_value = 42
assert_type(some_value, Optional[int])
# mypy: Expression is of type "Any", not "Optional[int]"
# [assert-type]
# mypy: Name "some_value" is not defined [name-defined]
assert some_value == 42
# mypy: Name "some_value" is not defined [name-defined]
# works at runtime
print("all is well") # is printed
if __name__ == '__main__':
in_a_function()
Expected Behavior
This code should produce no errors. (Analogous code, outside a def, is analyzed correctly.)
Actual Behavior
See: mypy's output, inline as comments.
Your Environment
- Mypy version used: 1.8.0
- Mypy command-line flags: none
- Mypy configuration options from
mypy.ini(and other config files): none - Python version used: 3.8, 3.12
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
提供された reproducer から始め、issue にリンクされている類似のトップレベルクラスの例とその動作を比較します。関数内にネストされたクラスでの nonlocal 宣言を mypy がどのように処理するかを追跡し、クラスの後でも外側の変数が型付けされたまま使用可能であることを示す回帰テストを追加します。reproducer がエラーを生成しなければ完了です。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- python
- 領域
- devtools
- issue の種類
- バグ
- 難易度
- 3/5
- 見積もり時間
- 1〜2日
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 45/100