ty
ty copied to clipboard
Emit diagnostic on constructor call to class with abstract methods
from abc import abstractmethod
class Base:
@abstractmethod
def f(self): ...
class BadChild(Base): ...
class GoodChild(Base):
def f(self): ... # concrete override
Base() # ❌ has abstract methods
BadChild() # ❌ has abstract methods
GoodChild() # ✅ abstract methods were overridden
class OtherBase:
@property
@abstractmethod
def prop(self) -> int:
return 42
OtherBase() # ❌ has abstract methods
class ThirdBase:
@property
def prop(self) -> int:
return 42
@prop.setter
@abstractmethod
def prop(self, x: int) -> None: ...
ThirdBase() # ❌ has abstract methods
The runtime only enforces this rule if the class has abc.ABCMeta (or a subclass) as its metaclass. But other type checkers also enforce it even if the decorator is used on a method in a class that does not have that metaclass. That's useful in stubs: there are situations where you want to indicate that you're meant to override a method (so you add the decorator), but the runtime version of the class doesn't have ABCMeta as the metaclass and you don't want to lie about the class's metaclass in the stub file.
Mypy's tests for this feature are at https://github.com/python/mypy/blob/master/test-data/unit/check-abstract.test