Sub topic 5
Sharing Behavior with Concrete Methods
This chapter assumes you can write classes with inheritance, and that you know @abstractmethod and the TypeError Python raises when you instantiate an incomplete subclass. It also assumes you can read basic try/except code.
An abstract base class (ABC) does not have to be a list of empty promises. It can also carry working code. A method with a normal body in an ABC is a concrete method. This chapter shows how concrete methods remove duplication, how they call the abstract methods, and which mistakes to avoid.
Abstract methods and concrete methods side by side
An ABC has two kinds of members:
- Abstract methods declare what a subclass must supply. The ABC cannot know the right answer, so it leaves the body to the subclass.
- Concrete methods are ordinary methods that every subclass inherits. They can call the abstract methods, because by the time an object exists, Python has already checked that every abstract method is implemented.
That guarantee is what makes concrete methods useful. A concrete method can call self.area() and be sure that area exists and is overridden.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self) -> float:
"""Return the area of the shape."""
def describe(self) -> str:
return f"{type(self).__name__} with area {self.area():.2f}"
class Rectangle(Shape):
def __init__(self, width: float, height: float) -> None:
self.width = width
self.height = height
def area(self) -> float:
return self.width * self.height
class Broken(Shape):
pass
print(Rectangle(2, 3).describe())
try:
Broken()
except TypeError as exc:
print("TypeError:", exc)describe is written once in Shape. Rectangle inherits it and gets Rectangle with area 6.00 without any extra code. Broken does not override area, so it stays abstract and Broken() raises TypeError. The error message names the missing method.
The template method pattern
When a concrete method fixes the order of steps and leaves some steps abstract, you have the template method pattern. The base class owns the algorithm. Subclasses fill in the steps that differ.
The next example exports rows of data. Validation and the overall layout are the same for every format. Only the formatting of a single row differs. The base class also offers two optional steps, header and footer, with default bodies.
from abc import ABC, abstractmethod
class Exporter(ABC):
def export(self, rows: list[dict]) -> str:
if not rows:
raise ValueError("no rows to export")
lines = list(self.header(rows))
lines.extend(self.format_row(row) for row in rows)
lines.extend(self.footer(rows))
return "\n".join(lines)
@abstractmethod
def format_row(self, row: dict) -> str:
"""Turn one row into one line of output."""
def header(self, rows: list[dict]) -> list[str]:
return []
def footer(self, rows: list[dict]) -> list[str]:
return []
class CsvExporter(Exporter):
def header(self, rows: list[dict]) -> list[str]:
return [",".join(rows[0])]
def format_row(self, row: dict) -> str:
return ",".join(str(value) for value in row.values())
class TextExporter(Exporter):
def format_row(self, row: dict) -> str:
pairs = ", ".join(f"{key}={value}" for key, value in row.items())
return f"- {pairs}"
def footer(self, rows: list[dict]) -> list[str]:
return [f"{len(rows)} rows"]
data = [{"name": "Ada", "age": 36}, {"name": "Alan", "age": 41}]
print(CsvExporter().export(data))
print(TextExporter().export(data))The output is:
name,age
Ada,36
Alan,41
- name=Ada, age=36
- name=Alan, age=41
2 rowsEach subclass is short, and neither repeats the validation or the line joining. If you later change how lines are joined, you edit one method.
The methods play different roles:
| Method | Kind | Subclass must override? |
|---|---|---|
| `export` | Concrete, the template | No, and usually should not |
| `format_row` | Abstract | Yes, or the subclass cannot be instantiated |
| `header`, `footer` | Concrete with a default, called hooks | Only if the default is wrong |
The distinction between abstract methods and hooks matters in design. Make a step abstract when no sensible default exists. Make it a hook when "do nothing" or a common default is a valid answer.
Abstract methods can have bodies
@abstractmethod only marks the method as required to override. It does not stop you from writing a body. A subclass must still override the method, but it can call the base version with super(). This is useful when the base class has a sensible common part and each subclass adds to it.
from abc import ABC, abstractmethod
class Greeter(ABC):
@abstractmethod
def greet(self, name: str) -> str:
return f"Hello, {name}"
class LoudGreeter(Greeter):
def greet(self, name: str) -> str:
return super().greet(name).upper() + "!"
print(LoudGreeter().greet("ada"))This prints HELLO, ADA!. The base body is shared, and the abstract marker forces every subclass to make a deliberate choice about the method, even if that choice is just return super().greet(name).
Use this sparingly. If most subclasses would just call super() unchanged, a plain concrete method is the clearer design.
Overriding concrete methods
Python does not stop a subclass from replacing a concrete method such as export. Nothing is enforced at runtime. This flexibility is sometimes wanted: a subclass might override describe to add detail. It can also break the contract of a template method, for example by skipping validation.
To state that a method is not meant to be overridden, you have two options:
- Document it: "Subclasses implement
format_row,headerandfooter, and should not overrideexport." - Mark it with
typing.final. Type checkers such as mypy then report any override. The decorator does not change runtime behavior, so Python itself still allows the override.
Pitfalls with concrete methods
Calling abstract methods from `__init__`
A concrete __init__ in the base class may call an abstract method. That method runs on the subclass, possibly before the subclass has set up its own attributes.
from abc import ABC, abstractmethod
class Base(ABC):
def __init__(self) -> None:
self.label = self.make_label()
@abstractmethod
def make_label(self) -> str:
"""Build a label for this object."""
class Good(Base):
def __init__(self, name: str) -> None:
self.name = name
super().__init__()
def make_label(self) -> str:
return f"<{self.name}>"
class Bad(Base):
def __init__(self, name: str) -> None:
super().__init__()
self.name = name
def make_label(self) -> str:
return f"<{self.name}>"
print(Good("a").label)
try:
Bad("b")
except AttributeError as exc:
print("AttributeError:", exc)Good sets self.name before calling super().__init__(), so it prints <a>. Bad calls the base constructor first, so make_label runs while self.name does not exist yet, and you get an AttributeError.
Writing a concrete method that needs more than the abstract interface
A concrete method should rely only on the abstract methods and on attributes the base class itself defines. If describe used self.width, it would work for Rectangle and fail with AttributeError for a Circle. When the base class method needs data, either declare it in the base __init__ or expose it through an abstract method or property (covered in a later chapter).
Expecting abstract checks on class definition
Python checks for unimplemented abstract methods when you create an instance, not when you define the class. Broken above is defined without error. The failure appears only at Broken(). A subclass that is never instantiated, such as an intermediate base class, can stay incomplete on purpose.
Duplicating logic instead of sharing it
If two subclasses contain the same method body, that body probably belongs in the base class as a concrete method. If it only applies to some subclasses, consider a separate mixin class instead of putting it in the ABC, so the ABC stays a clean contract.
Mixin methods in the standard library
The standard library uses this approach heavily. The ABCs in collections.abc declare a few abstract methods and supply many concrete ones built on top of them. For example, Mapping needs only __getitem__, __iter__ and __len__, and gives you get, keys, items, values and in support for free. These inherited concrete methods are called mixin methods. A later chapter covers them in detail.
Design guidelines
- Keep the set of abstract methods small. Every abstract method is work for each subclass author.
- Build concrete methods from the abstract ones so the base class can be tested through any simple subclass.
- Name hooks clearly and document which methods are required, which are optional, and which should not be overridden.
- Test the shared behavior once, using a minimal concrete subclass defined in the test.
Exercise
A base class Report(ABC) has a concrete method render that calls self.title() and self.body(), both abstract. A subclass Sales overrides body but forgets title. At which line does Python raise an error: when Sales is defined, when Sales() is called, or when render runs? What is the exception type?
Show answer
Python raises TypeError when Sales() is called, because title is still abstract and so Sales cannot be instantiated. Defining the class raises nothing, and render is never reached because no instance can be created.
Exercise
Add a hook to Exporter named sort_key that returns None by default. Change export so that, if sort_key(rows) returns a callable, the rows are sorted with it before formatting. What should the type of the hook's return value be, and why is it a hook rather than an abstract method?
Show answer
The return type is Callable[[dict], Any] | None. In export, write key = self.sort_key(rows), then if key is not None: rows = sorted(rows, key=key). It is a hook because "keep the original order" is a valid default, so subclasses should not be forced to implement it.