Sub topic 4
What happens when you instantiate an incomplete subclass
This chapter assumes you can define classes and use inheritance, and that you have seen @abstractmethod on an ABC subclass. Here you will learn exactly when Python enforces the abstract-method contract, what the error tells you, and which edge cases bypass or surprise the check.
Enforcement happens at instantiation, not at definition
Defining a subclass that omits abstract methods is legal. Python complains only when you try to create an object from it.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self) -> float:
"""Return the area."""
@abstractmethod
def perimeter(self) -> float:
"""Return the perimeter."""
class Square(Shape):
def __init__(self, side: float) -> None:
self.side = side
def area(self) -> float:
return self.side ** 2
print("Square class defined without error")
print(sorted(Shape.__abstractmethods__))
print(sorted(Square.__abstractmethods__))
try:
Square(2)
except TypeError as exc:
print("TypeError raised")
print(exc)The class statement for Square succeeds. The first two print calls show ['area', 'perimeter'] and then ['perimeter']. Only the Square(2) call raises TypeError.
This lazy timing is deliberate. An intermediate class in a hierarchy may stay incomplete on purpose, because it only fills in some of the required methods for its own subclasses to finish.
How the check works
ABCMeta is the metaclass behind ABC. When it creates a class, it computes a frozenset of the names that are still abstract and stores it in __abstractmethods__. The computation has two steps:
- Collect every name in the new class's namespace whose value has a true
__isabstractmethod__attribute.@abstractmethodsets that attribute. - For each name in the base classes'
__abstractmethods__, look the name up on the new class. If the value found still has__isabstractmethod__set to true, the name stays abstract. Otherwise a concrete override has resolved it.
The enforcement itself is in object.__new__. When you call a class, Python calls __new__ first and then __init__. object.__new__ checks whether the class has the Py_TPFLAGS_IS_ABSTRACT flag, which ABCMeta sets when __abstractmethods__ is not empty. If the flag is set, it raises TypeError.
One consequence is that __init__ never runs for an incomplete class. The next example shows it.
from abc import ABC, abstractmethod
class Job(ABC):
def __init__(self) -> None:
print("Job.__init__ ran")
@abstractmethod
def run(self) -> None:
...
class HalfDone(Job):
pass
try:
HalfDone()
except TypeError:
print("blocked before __init__")The output is only blocked before __init__. Side effects in __init__, such as opening files or connections, do not happen on a failed instantiation.
Reading the error message
The message names the class and the missing methods. The wording changed in Python 3.12:
- Python 3.9 to 3.11:
Can't instantiate abstract class Square with abstract method perimeter - Python 3.12 and later:
Can't instantiate abstract class Square without an implementation for abstract method 'perimeter'
If several methods are missing, the message lists all of them, in sorted order. Do not match on the message text in tests or error handlers. Catch TypeError, or inspect __abstractmethods__ when you need the names.
What counts as "implemented"
Python does not check signatures, return types, or that the override is a function. It only checks whether the name now resolves to something without a true __isabstractmethod__.
from abc import ABC, abstractmethod
class Handler(ABC):
@abstractmethod
def handle(self, event: str) -> str:
...
class WrongSignature(Handler):
def handle(self) -> str: # different parameters, still accepted
return "ok"
class Placeholder(Handler):
handle = None # not a method at all, still accepted
print(WrongSignature().handle())
print(Placeholder().handle)Both classes instantiate. The first prints ok and the second prints None. An ABC guarantees that names exist, not that they are usable. Use a type checker such as mypy or pyright to verify signatures.
The reverse also holds. Overriding an abstract method and calling super() is allowed, because abstract methods may have real bodies:
from abc import ABC, abstractmethod
class Logger(ABC):
@abstractmethod
def write(self, message: str) -> None:
print(f"[base] {message}")
class ConsoleLogger(Logger):
def write(self, message: str) -> None:
super().write(message)
print(f"[console] {message}")
ConsoleLogger().write("hello")The subclass must still define write. The base body is only reachable through an explicit super() call.
Abstract classes with no abstract methods
The ABC base does not by itself block instantiation. Only a non-empty __abstractmethods__ does.
from abc import ABC
class Marker(ABC):
pass
print(Marker())
print(Marker.__abstractmethods__)This creates a Marker instance and prints frozenset(). If you want a class that can never be instantiated but has no abstract methods, you need to add at least one abstract method, or raise an error in __new__ yourself.
Inheritance chains and partial completion
Each level removes the names it implements and adds any new abstract ones. A concrete class is the first one in the chain where the set becomes empty.
from abc import ABC, abstractmethod
class Reader(ABC):
@abstractmethod
def open(self) -> None: ...
@abstractmethod
def read(self) -> str: ...
class FileReader(Reader):
def open(self) -> None:
print("opening")
class TextFileReader(FileReader):
def read(self) -> str:
return "text"
print(sorted(Reader.__abstractmethods__))
print(sorted(FileReader.__abstractmethods__))
print(sorted(TextFileReader.__abstractmethods__))
TextFileReader().open()The three sets are ['open', 'read'], ['read'] and []. FileReader is still abstract, and TextFileReader is the first class you can instantiate.
With multiple inheritance, Python uses the method resolution order (MRO) to find the name. A concrete method found earlier in the MRO satisfies an abstract one that appears later.
Where the check does not apply
| Situation | Is it checked? |
|---|---|
| Defining a subclass with missing methods | No, only instantiation is checked |
| Calling the class, such as `Square(2)` | Yes |
| Calling an abstract `@classmethod` on the class itself | No, the call runs the method body |
| A class whose metaclass is not `ABCMeta` | No, `@abstractmethod` has no effect |
| A class registered with `register` | No, see the chapter on virtual subclasses |
| Creating objects with `object.__new__(cls)` directly | Yes, because the check lives in `object.__new__` |
The fourth row catches many people. Without ABCMeta, the decorator only sets an attribute that nothing reads.
from abc import abstractmethod
class NotReallyAbstract: # no ABC, no ABCMeta
@abstractmethod
def work(self) -> None:
...
obj = NotReallyAbstract()
print("created without error:", type(obj).__name__)This prints created without error: NotReallyAbstract. Always inherit from ABC or set metaclass=ABCMeta.
Changing a class after creation
__abstractmethods__ is computed once, when the class is created. If you add or replace attributes later, the set does not update on its own. Since Python 3.10, abc.update_abstractmethods recomputes it.
from abc import ABC, abstractmethod, update_abstractmethods
class Widget(ABC):
pass
Widget.draw = abstractmethod(lambda self: None)
print(Widget.__abstractmethods__)
Widget() # still allowed, the set is stale
update_abstractmethods(Widget)
print(Widget.__abstractmethods__)
try:
Widget()
except TypeError:
print("now blocked")The output is frozenset(), then frozenset({'draw'}), then now blocked. The function is also applied automatically to classes decorated with functools.total_ordering and dataclasses.dataclass, because those decorators add methods after the class is built.
Handling the error in practice
In application code, a TypeError from an incomplete subclass is a programming error, so you usually let it propagate. Two cases justify catching it:
- A plugin loader that imports third-party classes and wants to report which plugin is broken.
- A test that confirms a base class really is abstract.
from abc import ABC, abstractmethod
class Plugin(ABC):
@abstractmethod
def start(self) -> None: ...
@abstractmethod
def stop(self) -> None: ...
class Good(Plugin):
def start(self) -> None: ...
def stop(self) -> None: ...
class Bad(Plugin):
def start(self) -> None: ...
def load(plugin_cls: type[Plugin]) -> Plugin:
missing = sorted(getattr(plugin_cls, "__abstractmethods__", ()))
if missing:
raise ValueError(f"{plugin_cls.__name__} lacks: {', '.join(missing)}")
return plugin_cls()
print(type(load(Good)).__name__)
try:
load(Bad)
except ValueError as exc:
print(exc)The loader reports Bad lacks: stop without depending on the interpreter's error wording.
Summary of the model
ABCMetacomputes__abstractmethods__when the class is created.object.__new__raisesTypeErrorif that set is not empty, before__init__runs.- Any non-abstract value under the same name satisfies the contract, whatever its signature.
- Without
ABCMeta,@abstractmethoddoes nothing.
Exercise
A class Base(ABC) has one abstract method go. Mid(Base) adds a concrete method stop but does not define go. Leaf(Mid) defines go. Which of the three classes can be instantiated, and what is Mid.__abstractmethods__?
Show answer
Only Leaf can be instantiated. Mid.__abstractmethods__ is frozenset({'go'}), so Mid() raises TypeError. Defining Mid itself raises no error, because the check runs only at instantiation.
Exercise
You write class Task: @abstractmethod def run(self): ... without inheriting from ABC, then call Task(). What happens, and how do you fix it?
Show answer
Nothing is raised and the object is created, because the class's metaclass is type, not ABCMeta, so __abstractmethods__ is never computed. Fix it by writing class Task(ABC): or class Task(metaclass=ABCMeta):.