False negative for invalid abstractmethod implementation
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
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?
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the provided Python reproduction and inspect mypy's abstractmethod and ABC handling; no source files or tests are named in the issue. Done when mypy rejects the instance-attribute implementations shown and preserves the intended behavior for abstractmethod on non-ABC classes.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100