python / python/mypy

Should a method name shadow outer names when quoted or with PEP563?

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

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

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

説明

Bug Report

If a class defines a method with a name shadowing outer name, mypy always rejects it in annotations.

To Reproduce

Consider the following snippet (playground):

#from __future__ import annotations

from typing import get_type_hints, get_origin

class Foo:
    def list(self) -> None: ...
    
    def method(self) -> list[str]:  # E: Function "__main__.Foo.list" is not valid as a type  [valid-type]
        return [""]

Foo().method().append("")  # E: "list?[builtins.str]" has no attribute "append"  [attr-defined]

if get_origin(get_type_hints(Foo.method)['return']) is list:
    print("Resolved to builtins.list")
else:
    print("Resolved as something else")

When run against it, mypy is producing a correct valid-type error, matching runtime behaviour.

$ mypy a.py
a.py:8: error: Function "a.Foo.list" is not valid as a type  [valid-type]
a.py:8: note: Perhaps you need "Callable[...]" or a callback protocol?
a.py:11: error: "list?[builtins.str]" has no attribute "append"  [attr-defined]
Found 2 errors in 1 file (checked 1 source file)

$ pyright a.py
/tmp/tmp.StzhaQlnmA/a.py
  /tmp/tmp.StzhaQlnmA/a.py:8:25 - error: Expected class but received "(self: Self@Foo) -> None" (reportGeneralTypeIssues)
1 error, 0 warnings, 0 informations 

$ python a.py
Traceback (most recent call last):
  File "/tmp/tmp.StzhaQlnmA/a.py", line 5, in <module>
    class Foo:
    ...<3 lines>...
            return [""]
  File "/tmp/tmp.StzhaQlnmA/a.py", line 8, in Foo
    def method(self) -> list[str]:  # E: Function "__main__.Foo.list" is not valid as a type  [valid-type]
                        ~~~~^^^^^
TypeError: 'function' object is not subscriptable

Now let's uncomment the future import or quote list[int] (both behave equivalently).

from __future__ import annotations

from typing import get_type_hints, get_origin

class Foo:
    def list(self) -> None: ...
    
    def method(self) -> list[str]:  # E: Function "__main__.Foo.list" is not valid as a type  [valid-type]
        return [""]

Foo().method().append("")  # E: "list?[builtins.str]" has no attribute "append"  [attr-defined]

if get_origin(get_type_hints(Foo.method)['return']) is list:
    print("Resolved to builtins.list")
else:
    print("Resolved as something else")
$ mypy a.py
a.py:8: error: Function "a.Foo.list" is not valid as a type  [valid-type]
a.py:8: note: Perhaps you need "Callable[...]" or a callback protocol?
a.py:11: error: "list?[builtins.str]" has no attribute "append"  [attr-defined]
Found 2 errors in 1 file (checked 1 source file)

$ pyright a.py
0 errors, 0 warnings, 0 informations 

$ python a.py
Resolved to builtins.list

Runtime resolution also (unsurprisingly, probably) works as intended, so mypy does not model runtime semantics correctly?

Expected Behavior

Snippet with PEP563 enabled should pass mypy check

Actual Behavior

a.py:8: error: Function "a.Foo.list" is not valid as a type  [valid-type]
a.py:8: note: Perhaps you need "Callable[...]" or a callback protocol?
a.py:11: error: "list?[builtins.str]" has no attribute "append"  [attr-defined]
Found 2 errors in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 1.14.1 and latest master
  • Mypy command-line flags: N/A
  • Mypy configuration options from mypy.ini (and other config files): N/A
  • Python version used: 3.13

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

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

はじめの一歩

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

調査の方向性

まず、提供された再現コードに対して、アノテーションを引用符で囲んだ場合と囲まない場合、または PEP 563 を有効にした場合としない場合に mypy を実行し、その結果を実行時の解決結果および pyright と比較します。外側の名前をシャドーイングするメソッド名について、アノテーションの名前解決パスを追跡します。次に、提示されたケースのカバレッジを追加し、想定されるチェックが通ることを確認します。

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

評価

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

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

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