False negative for invalid abstractmethod implementation
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
Bug Report
If a subclass of an ABC implements an abstractmethod as an attribute (e.g. not as method or class variable), (and the subclass is instantiated,) then mypy passes. But it will always fail at runtime (as ABCMeta can only detect variables/methods on the class).
There are only some cases where this can happen because implementing a method as an attribute would yield a mypy type error most of the time:
- an abstract property is implemented as a normal instance attribute
- an abstract method is implemented as a function instance attribute
Note: these implementations are valid both pragmatically and for type-checking, but ABCMeta is obligated to raise an error because it cannot detect the implementation.
To Reproduce
The following program will pass in mypy but fail at runtime.
from abc import abstractmethod, ABC
from collections.abc import Callable
class Method(ABC):
@abstractmethod
def f(self) -> None:
...
class ImplMethod(Method):
f: Callable[[], None]
def __init__(self):
self.f = print
ImplMethod()
class Property(ABC):
@property
@abstractmethod
def x(self) -> int:
...
class ImplProperty(Property):
x: int
def __init__(self):
self.x = 2
ImplProperty()
Expected Behavior
Error at runtime.
Mypy should error too because the implementations do not satisfy abstractmethod at runtime.
Actual Behavior
Error at runtime.
Mypy success.
Your Environment
- Mypy version used: latest (1.11.1), with default playground flags
- Python version used: 3.12.4
Also:
It seems like mypy doesn't complain when using abstractmethod on a non-ABC class. This is intended, right?
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginne mit der bereitgestellten Python-Reproduktion und untersuche mypys Behandlung von abstractmethod und ABC; in der Issue werden keine Quelldateien oder Tests genannt. Die Aufgabe ist abgeschlossen, wenn mypy die gezeigten Implementierungen von Instanzattributen ablehnt und das beabsichtigte Verhalten von abstractmethod bei Nicht-ABC-Klassen beibehält.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- devtools
- Issue-Typ
- Bug
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 45/100