python / python/mypy

False positive comparison-overlap for nested function and nested class

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

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

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

説明

Bug Report

Nested functions inside methods incorrectly resolve attributes of their first argument relative to the surrounding class.

To Reproduce

class foo:
    a: str = "foo"
    
class bar:
    class a:
        pass
    
    def test(self) -> None:
        def inner1(f: foo, s: str) -> bool:
            return f.a == s
        
        def inner2(s: str, f: foo) -> bool:
            return f.a == s

https://mypy-play.net/?mypy=latest&python=3.11&flags=strict&gist=4c27f653074cd1c3a48bb16f49ca2168

Expected Behavior

As far as I can tell this should be valid code, even though this rarely happens in practice due to CamelCase vs snake_case naming conventions.

Actual Behavior

inner1 fails to type-check, because the a attribute is incorrectly assumed to be the a class inside bar

main.py:10: error: Non-overlapping equality check (left operand type: "Type[a]", right operand type: "str")  [comparison-overlap]

Interestingly, inner2 is fine.

Your Environment

  • Mypy version used: 1.2.0
  • Mypy command-line flags: --strict
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.11

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

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

はじめの一歩

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

調査の方向性

Python 3.11 と --strict を使って mypy で issue の例を再現し、その後、ネストされた関数が比較内の属性アクセスをどのように解決するかを追跡します。inner1 が comparison-overlap エラーを報告しなくなり、inner2 が引き続き有効で、回帰がテストでカバーされれば修正完了です。

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

評価

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

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

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