Sub topic 4
What happens when you instantiate an incomplete subclass
This chapter assumes you can write classes with inheritance, know the @abstractmethod decorator from the previous chapter, and can handle exceptions with try/except.
When the check runs
Python does not check for missing methods when you define a subclass. It checks when you create an instance. A subclass that leaves abstract methods unimplemented is still a valid class. It is just an abstract one, and you can use it as a base for further subclasses.
The check involves two steps:
- When a class is created,
ABCMetacollects every name still marked abstract into a frozenset stored in__abstractmethods__. - When you call the class,
object.__new__looks at that set. If it is not empty, it raisesTypeErrorbefore__init__runs.
A worked example
from abc import ABC, abstractmethod
class Storage(ABC):
@abstractmethod
def read(self, key):
...
@abstractmethod
def write(self, key, value):
...
class ReadOnly(Storage):
def read(self, key):
return key.upper()
print(sorted(Storage.__abstractmethods__))
print(sorted(ReadOnly.__abstractmethods__))
print("ReadOnly class defined without error")
try:
ReadOnly()
except TypeError as exc:
print("TypeError:", exc)
class Memory(Storage):
def __init__(self):
self._data = {}
def read(self, key):
return self._data[key]
def write(self, key, value):
self._data[key] = value
store = Memory()
store.write("a", 1)
print(store.read("a"), Memory.__abstractmethods__)Running this prints:
['read', 'write']
['write']
ReadOnly class defined without error
TypeError: Can't instantiate abstract class ReadOnly without an implementation for abstract method 'write'
1 frozenset()ReadOnly overrides read, so only write remains in its set. Memory overrides both, so its set is empty and instantiation works.
The error text depends on your Python version. Before 3.12 it reads Can't instantiate abstract class ReadOnly with abstract method write. If several methods are missing, both versions list all of them.
Reading the error
The message names the class you tried to instantiate and every method it still lacks. Fix it by implementing those methods in that class or in a base class between it and the ABC.
Three details often cause confusion:
- Overriding with a non-method counts. If a subclass assigns
read = Noneor definesreadas a plain attribute, the name leaves the abstract set. Python checks that a name is no longer decorated as abstract. It does not check that the replacement is callable. - Implementing inherited abstract names is enough. A name is cleared by any override in the subclass's own namespace, even one that only calls
super().read(key). Abstract methods may have bodies, so that call is legal. - The error comes from the call, not from
__init__. Your__init__never runs for an incomplete class, so side effects such as opening files do not happen.
Where enforcement stops
The check lives in object.__new__. A class that defines its own __new__ and never calls object.__new__ skips it. This is rare and usually a bug.
The set is also computed once, when the class is created. If you attach a method to a class afterwards, __abstractmethods__ does not update on its own. In Python 3.10 and later, abc.update_abstractmethods(cls) recomputes it.
Testing for it
You can assert the behavior directly, which is useful when an interface is part of your public API:
import inspect
from abc import ABC, abstractmethod
class Base(ABC):
@abstractmethod
def run(self):
...
class Incomplete(Base):
pass
print(inspect.isabstract(Base))
print(inspect.isabstract(Incomplete))
print(sorted(Incomplete.__abstractmethods__))All three lines report that the class is abstract: True, True, then ['run']. inspect.isabstract is a cleaner check than reading the flag yourself.
Exercise
A class Base(ABC) has abstract methods a and b. Class Mid(Base) implements only a. Class Leaf(Mid) implements b. Which of Base(), Mid() and Leaf() raise TypeError, and what does Mid._abstractmethods_ contain?
Show answer
Base() and Mid() raise TypeError, because each still has unimplemented abstract names. Leaf() succeeds because a is implemented in Mid and b in Leaf, so its set is empty. Defining Mid raises no error. Mid._abstractmethods_ is frozenset({'b'}).