python / python/mypy

Mypy not detecting abstract methods returning undefined types

Offen
#14,545 1 Kommentar 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

bug topic-runtime-semantics
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

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

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Reproduziere das Verhalten aus test.py, indem du mypy --strict und anschließend Python ausführst, um das statische Ergebnis mit dem Laufzeit-NameError zu vergleichen. Verfolge, wie mypy die Rückgabeannotationen der abstrakten Methode analysiert, bevor Result deklariert ist. Als abgeschlossen gilt dies, wenn mypy in diesem Fall die nicht definierte Result-Referenz meldet, ohne gültige Annotationen zu beeinträchtigen.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
devtools
Issue-Typ
Bug
Schwierigkeit
3/5
Geschätzter Aufwand
1-2 Tage
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
45/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.