Sub topic 11
Defining interfaces with abstract base classes
This chapter assumes you can write classes with __init__, use inheritance and super(), and understand polymorphism and duck typing. It covers how to declare a required interface with an abstract base class (ABC), and what Python does to enforce it.
Why an interface needs enforcement
Duck typing works well when every class you pass around happens to have the right methods. When you write a base class that expects subclasses to fill in a method, a plain base class fails late. A subclass that forgets the method only breaks when someone calls it, possibly deep in a program.
An abstract base class moves that failure to the moment of instantiation. You mark methods as required, and Python refuses to create an object until every required method has an implementation.
Declaring an abstract class
Inherit from ABC in the abc module and decorate required methods with @abstractmethod.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
...
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
print(Square(3).area()) # 9
try:
Shape()
except TypeError as exc:
print("cannot instantiate:", exc)Square overrides area, so it is concrete and can be instantiated. Shape still has an abstract method, so Shape() raises TypeError.
The check happens in object.__new__, using a set of unimplemented names stored on the class as __abstractmethods__. Defining the subclass never fails. Only instantiation does.
What the decorator does and does not do
@abstractmethodonly has an effect when the class's metaclass isABCMeta. Inheriting fromABCsets that for you.- The abstract method can have a body. Subclasses can call it with
super(), which is useful for shared default behavior. - It does not check signatures. A subclass can override
area(self, scale, extra)and Python will accept it. - It does not check return values.
from abc import ABC, abstractmethod
class Report(ABC):
@abstractmethod
def title(self):
return "Untitled"
def render(self):
return f"== {self.title()} =="
class Sales(Report):
def title(self):
return "Sales, " + super().title()
print(Sales().render()) # == Sales, Untitled ==Here render is a concrete method that relies on the abstract title. This pattern is often called the template method: the base class fixes the overall steps, and subclasses supply the pieces.
Abstract properties
To require an attribute-like member, stack @property on top of @abstractmethod. Put @property first (outermost).
from abc import ABC, abstractmethod
class Named(ABC):
@property
@abstractmethod
def name(self):
...
class User(Named):
@property
def name(self):
return "ada"
print(User().name) # adaThe same ordering rule applies to @classmethod and @staticmethod: the abstract decorator goes innermost, next to def.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `TypeError: Can't instantiate abstract class ...` | A subclass did not override every abstract method | Implement all names listed in the message |
| Abstract method is not enforced | Class inherits from a plain class, not `ABC` | Inherit from `ABC` or use `metaclass=ABCMeta` |
| Abstract property is ignored | Decorators in the wrong order | Put `@property` above `@abstractmethod` |
| Subclass has a typo in the method name | The new name is just an extra method | The error on instantiation reveals the missing original name |
ABCs, protocols, and duck typing
You can also check types with isinstance(obj, Shape). Subclasses pass that test, which lets code branch on the interface rather than on concrete classes.
Exercises
Exercise
You define class Base(ABC) with an @abstractmethod named run. A subclass Job(Base) defines rnu (a typo) instead of run. Does the error occur when the Job class is defined or when Job() is called, and why?
Show answer
It occurs when Job() is called. Defining the class succeeds, because Python only checks the abstract-method set at instantiation. Job never overrode run, so run is still abstract and Job() raises TypeError.
Exercise
Write an abstract class Exporter with an abstract method export(self, data) and a concrete method export_all(self, items) that returns a list of self.export(item) for each item. Then write a subclass that makes export_all([1, 2]) return ["1", "2"].
Show answer
from abc import ABC, abstractmethod class Exporter(ABC): @abstractmethod def export(self, data): ... def exportall(self, items): return [self.export(item) for item in items] class TextExporter(Exporter): def export(self, data): return str(data) print(TextExporter().exportall([1, 2])) # ['1', '2']