python / python/mypy

Mypy not detecting abstract methods returning undefined types

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

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

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

説明

Bug Report

I have a class with a couple of abstract methods that return a particular custom type. That custom type is then defined right after the class. Then a global variable referencing that class is created:

To Reproduce

# test.py
from abc import ABC, abstractmethod
from typing import NamedTuple, List

class F(ABC):
    @abstractmethod
    async def m1(self) -> Result:
        pass
    
    @abstractmethod
    async def m2(self) -> Result:
        pass

class Result(NamedTuple):
    f1: str
    f2: int
    
foo: List[F] = []
> mypy --strict test.py
Success: no issues found in 1 source file
> python test.py
Traceback (most recent call last):
  File "test.py", line 4, in <module>
    class F(ABC):
  File "test.py", line 6, in F
    async def m1(self) -> Result:
NameError: name 'Result' is not defined

Expected Behavior

I would expect mypy to detect that Result is not defined before its use in class F.

Actual Behavior

Mypy is happy with the code as it is, even under --strict, while Python can't even run the code as is. Moving the declaration of Result above class F solves the problem and both Python and mypy are then happy.

Your Environment

  • Mypy version used: 0.991
  • Mypy command-line flags: --strict
  • Mypy configuration options from mypy.ini (and other config files): N/A
  • Python version used: 3.9.13

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

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

はじめの一歩

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

調査の方向性

mypy --strict を実行してから Python を実行し、静的な結果と実行時の NameError を比較することで、test.py の動作を再現します。Result が宣言される前に、mypy が抽象メソッドの戻り値アノテーションをどのように解析するかを追跡します。このケースで、mypy が未定義の Result 参照を報告しつつ、有効なアノテーションを壊さなければ完了です。

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

評価

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

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

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