Sub topic 11
Defining interfaces with abstract base classes
This chapter assumes you are comfortable with inheritance, super(), and method overriding, and that you know what duck typing is. It builds on the chapters on inheritance and polymorphism.
An abstract base class (ABC) is a class that declares which methods its subclasses must provide and refuses to be instantiated until they do. It turns a convention ("every shape has an area()") into a rule that Python enforces.
Why declare an interface
Duck typing is flexible but fails late. If you pass an object without the right method into a function, you get an AttributeError only when that line runs. That can be deep inside a program, long after the object was created.
An ABC moves the failure to the moment of instantiation. A subclass that forgets a required method cannot be created at all, so the mistake shows up at the first line that builds it.
Declaring an abstract base class
Inherit from abc.ABC and mark 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)ABC is a helper class whose metaclass is ABCMeta. When a class is created, ABCMeta collects every method flagged as abstract into a frozenset stored in __abstractmethods__. A subclass inherits that set, minus any names it overrides with concrete implementations. When you call the class, object.__new__ checks whether the set is empty. If it is not, it raises TypeError.
The exact wording of the error message differs between Python versions. Do not match on it in tests.
Partial implementations stay abstract
A subclass that implements only some of the abstract methods is itself still abstract. You can build several layers of hierarchy, and only the leaf classes need to be complete.
import math
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
...
@abstractmethod
def perimeter(self):
...
def describe(self):
return (f"{type(self).__name__}: "
f"area={self.area():.2f}, perimeter={self.perimeter():.2f}")
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
def perimeter(self):
return 2 * math.pi * self.radius
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
# perimeter() is missing
print(Circle(1).describe()) # Circle: area=3.14, perimeter=6.28
print(sorted(Shape.__abstractmethods__)) # ['area', 'perimeter']
print(sorted(Square.__abstractmethods__)) # ['perimeter']
try:
Square(2)
except TypeError:
print("Square is still abstract")describe() is a concrete method defined on the ABC. It calls the abstract methods through self, so every subclass gets it for free. This pattern, a fixed algorithm in the base class that calls hooks the subclasses fill in, is called the template method pattern. It is the most common reason to prefer an ABC over a bare interface.
Abstract properties and classmethods
Abstract methods can also be properties, classmethods, or staticmethods. Stack @abstractmethod as the innermost decorator, directly above the def.
from abc import ABC, abstractmethod
class Plugin(ABC):
@property
@abstractmethod
def name(self):
...
@classmethod
@abstractmethod
def create(cls):
...
class Greeter(Plugin):
name = "greeter" # a plain class attribute satisfies the abstract property
@classmethod
def create(cls):
return cls()
print(Greeter.create().name) # greeterPython decides whether a name is still abstract by looking at the attribute the subclass actually provides. A plain string has no abstract flag, so name = "greeter" is enough. Subclasses are free to implement an abstract property as a property, a class attribute, or an instance attribute set in __init__. The last case is the exception, because the check runs before __init__. An instance attribute does not clear the abstract flag, so it must be a class-level name.
If you reverse the decorator order, writing @abstractmethod above @property, the method is no longer reported as abstract and nothing is enforced.
Abstract methods can have a body
An abstract method may contain real code. The subclass must still override it, but it can call the base version with super().
from abc import ABC, abstractmethod
class Exporter(ABC):
@abstractmethod
def export(self, rows):
return "header\n" # shared default behavior
class CsvExporter(Exporter):
def export(self, rows):
body = "\n".join(",".join(map(str, row)) for row in rows)
return super().export(rows) + body
print(CsvExporter().export([(1, 2), (3, 4)]))
# header
# 1,2
# 3,4Virtual subclasses and `isinstance`
ABCs also change what isinstance() and issubclass() mean. The standard library's collections.abc module uses this heavily. Sized is satisfied by any class with __len__, and Iterable by any class with __iter__, with no inheritance involved.
from collections.abc import Iterable, Sized
class Playlist:
def __init__(self, songs):
self._songs = list(songs)
def __len__(self):
return len(self._songs)
def __iter__(self):
return iter(self._songs)
p = Playlist(["a", "b"])
print(isinstance(p, Sized), isinstance(p, Iterable)) # True TrueThese ABCs define a __subclasshook__ that inspects the candidate class for the right method names. You can also declare a relationship explicitly with register(), which is useful for classes you cannot edit.
from abc import ABC, abstractmethod
class Closeable(ABC):
@abstractmethod
def close(self):
...
class Legacy:
def close(self):
print("closed")
Closeable.register(Legacy)
print(isinstance(Legacy(), Closeable)) # True
print(issubclass(Legacy, Closeable)) # True
print(Closeable in Legacy.__mro__) # FalseA registered class is a virtual subclass. It passes isinstance checks, but it does not inherit anything, it does not appear in the MRO, and Python does not verify that it implements the abstract methods.
ABC, protocol, or plain duck typing
Python offers three ways to describe "an object that can do X". Pick based on who controls the classes and how much enforcement you need.
| Approach | Enforced when | Needs inheritance | Best for |
|---|---|---|---|
| Plain duck typing | When the method is called | No | Small scripts, internal helpers |
| ABC with `@abstractmethod` | On instantiation | Yes (or `register`) | Plugin systems, shared base behavior, frameworks |
| `typing.Protocol` | By a static type checker only | No | Typing code that accepts third-party classes |
Choose an ABC when subclasses must be written against your base class and you want shared concrete code (template methods) or a runtime error for incomplete subclasses. Choose a protocol when you only need type-checker help and cannot or do not want to force inheritance. Use plain duck typing when the interface is one method and the cost of a late failure is low.
Gotchas and edge cases
- Inheriting from
ABCis what activates enforcement. If a class does not useABCMeta,@abstractmethodis silently ignored. Writingclass Shape:with an abstract method gives no error onShape(). - Only names are checked. Python verifies that a concrete method with the right name exists. It does not check parameters or return values. A subclass
def area(self, extra)passes the check and breaks later. - Enforcement happens at instantiation, not at class definition. Defining an incomplete subclass is allowed. The error appears when you call it. Class-level tests that never instantiate will not catch the mistake.
- Abstract classes can still hold state. An ABC can define
__init__and attributes. Subclasses callsuper().__init__()as usual. - Metaclass conflicts. Combining an ABC with a class that uses a different metaclass raises
TypeError: metaclass conflict. Resolve it by deriving a combined metaclass, or switch to a protocol or composition. - Adding abstract methods later breaks subclasses. Every existing concrete subclass becomes abstract, and instantiating any of them fails. Treat the set of abstract methods as part of your public API.
Checking your understanding
Exercise
A class Base(ABC) has two abstract methods, load and save. Child(Base) implements only load. What happens on Child(), and what happens on Child.__abstractmethods__?
Show answer
Child() raises TypeError, because Child is still abstract. Child.__abstractmethods__ is frozenset({'save'}), since load was overridden with a concrete method.
Exercise
You have class Logger: with a write(self, text) method, defined in a third-party library you cannot edit. Your code defines class Sink(ABC) with an abstract write. How do you make isinstance(Logger(), Sink) return True, and what does Python not check when you do?
Show answer
Call Sink.register(Logger). Python does not check that Logger implements write, and Logger does not inherit anything from Sink.
Exercise
Why does this class fail to enforce anything, and how do you fix it? class Repo: @abstractmethod def get(self, key): ... Repo()
Show answer
Repo does not inherit from ABC and has no ABCMeta metaclass, so @abstractmethod has no effect and Repo() succeeds. Fix it by declaring class Repo(ABC): (or metaclass=ABCMeta).