One Skeleton, Many Steps: The Template Method Pattern in Python
This article explains how the Template Method pattern fixes the order of a procedure in a base class, how hooks and abstract steps let subclasses vary it, where the standard library applies it, and how to stop subclasses overriding the skeleton.
Several classes often perform the same procedure with small variations: exporters that validate, transform and format records, parsers that read, interpret and report, or test cases that prepare, run and clean up. Copying the procedure into each class duplicates the order of its steps, which then drifts apart as each copy is corrected separately. The present article examines the Template Method pattern, in which a base class fixes the skeleton of the procedure in one method and lets subclasses supply only the steps that vary. It builds a family of exporters, distinguishes required steps from optional hooks, shows the pattern in the standard library, compares it with passing functions, and analyses why Python does not by itself prevent a subclass from rewriting the skeleton. Writing the order of a procedure once, while each subclass fills in only what is different, is the secret weapon of the Template Method pattern.
A Skeleton with Replaceable Steps
The template method is an ordinary method of the base class that calls other methods in a fixed order; some of those methods are abstract, so every subclass must provide them, and others are implemented once in the base class. The inversion of control is the defining feature: the subclass does not call the base class to run the procedure; the base class calls the subclass at the moments it chooses. In the following example, the abstract methods are declared with the abc module, as described in the article devoted to abstract base classes.
import json
from abc import ABC, abstractmethod
class Exporter(ABC):
def export(self, records):
valid = [r for r in records if self.is_valid(r)]
rows = [self.transform(r) for r in valid]
return self.format(rows)
def is_valid(self, record):
return record.get("amount", 0) > 0
@abstractmethod
def transform(self, record): ...
@abstractmethod
def format(self, rows): ...
class CsvExporter(Exporter):
def transform(self, record):
return f"{record['id']},{record['amount']:.2f}"
def format(self, rows):
return "\n".join(["id,amount", *rows])
class JsonExporter(Exporter):
def transform(self, record):
return {"id": record["id"], "amount": round(record["amount"], 2)}
def format(self, rows):
return json.dumps(rows)
records = [{"id": 1, "amount": 12.5}, {"id": 2, "amount": 0}, {"id": 3, "amount": 7.25}]
print(CsvExporter().export(records))
# Output: id,amount
# Output: 1,12.50
# Output: 3,7.25
print(JsonExporter().export(records))
# Output: [{"id": 1, "amount": 12.5}, {"id": 3, "amount": 7.25}]
The validation rule and the order of the three steps live only in Exporter.export, so both formats discard the record with a zero amount without repeating the rule. A new format, such as XML, requires one subclass with two methods, and a subclass that forgets one of them cannot be instantiated, since abc reports the missing abstract method.
Hooks: Optional Steps with a Default
Many card games divide each turn into fixed phases, and a card may act "at the start of the turn" or "at the end of the turn" without changing the order of the phases. This means that a hook is a step that the template method always calls but whose default implementation does nothing, so that a subclass overrides it only when it needs to act at that moment. The analogy, however, stops at this point, because the rules of a game forbid a player to reorder its phases, whereas Python does not forbid a subclass to replace the template method itself, a limitation examined in the pitfalls. The standard library uses hooks extensively: html.parser.HTMLParser.feed runs the parsing algorithm and calls handle_starttag, handle_data and similar methods, whose defaults ignore the input, as the following example shows.
from html.parser import HTMLParser
class LinkCollector(HTMLParser):
def __init__(self):
super().__init__()
self.links = []
def handle_starttag(self, tag, attrs):
if tag == "a":
self.links.append(dict(attrs).get("href"))
collector = LinkCollector()
collector.feed('<p>See <a href="/docs">docs</a> and <a href="/faq">FAQ</a>.</p>')
print(collector.links) # Output: ['/docs', '/faq']
The subclass overrides one hook and ignores every other event of the parser, while feed keeps control of tokenizing, buffering and the order of the calls. The same structure appears in unittest.TestCase, which calls setUp, the test method and tearDown, and in socketserver.BaseRequestHandler, which calls setup, handle and finish.
Template Method and Strategy
This section compares the pattern with its closest alternative. A template method varies the steps through inheritance, so each combination of steps requires a subclass; the Strategy pattern, examined in the article devoted to the Strategy pattern, varies them through objects or functions passed in, so they can be combined and replaced at run time. In Python, where functions are values, a procedure whose steps vary independently is often clearer as a function that receives those steps as arguments; the template method remains appropriate when the steps share the state of an object, as the parser above shares its buffer and position, or when a framework must call user code at fixed moments.
Pitfalls of the Template Method Pattern
A template method makes the base class responsible for the whole procedure, so most of its errors come from subclasses that escape that control or from base classes that grow too large. Six pitfalls are distinguished, which are the following:
- Overriding the skeleton. A subclass can redefine the template method and skip or reorder steps;
typing.finaldocuments the intention, but Python does not enforce it at run time. - Forgetting to call the base implementation. A subclass that overrides a concrete step without calling
super()silently drops the work of the base class. - Too many steps. A skeleton divided into many small abstract methods forces every subclass to implement them all, even those that do not vary.
- Deep hierarchies. Templates that refine templates make it hard to know which class supplies each step.
- Hidden calls. Because the base class calls the subclass, a reader of the subclass cannot see when each method runs without reading the template.
- Inheritance for independent variations. When two steps vary independently, subclasses multiply; passing functions scales better.
The first pitfall is reproduced in the following example, together with an enforcement at class creation through __init_subclass__, the hook described in the article devoted to __init_subclass__.
from typing import final
class Report:
@final
def render(self):
return f"{self.header()} | {self.body()}"
def header(self):
return "REPORT"
class Shortcut(Report):
def render(self):
return "body only"
print(Shortcut().render()) # Output: body only
class StrictReport(Report):
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
for name, attribute in vars(Report).items():
if getattr(attribute, "__final__", False) and name in vars(cls):
raise TypeError(f"{cls.__name__} overrides final method {name!r}")
try:
class Rogue(StrictReport):
def render(self):
return "body only"
except TypeError as error:
print(error) # Output: Rogue overrides final method 'render'
The decorator typing.final only sets the attribute __final__, which static type checkers read, so the first subclass replaces the skeleton without any error. The second base class reads that attribute when each subclass is created and refuses the override, which turns the documented intention into a check that runs before any object exists.
Choosing How to Vary the Steps
Consequently, the pattern fits procedures whose order is fixed and whose varying steps share the state of an object, as the following table summarizes.
| Situation | Recommended approach |
|---|---|
| Fixed order, a few steps that differ per subclass | A template method with abstract steps |
| Optional actions at fixed moments | Hooks with empty default implementations |
| Steps that vary independently or at run time | Functions or strategy objects passed in |
| A framework that calls user code | A template method in the framework's base class |
| The skeleton must never be overridden | typing.final, enforced with __init_subclass__ if needed |
| A single variant | A plain function, without a hierarchy |
Conclusion
It is concluded that the Template Method pattern fixes the order of a procedure in one method of a base class and lets subclasses supply its varying steps and optional hooks, and that the standard library applies it in parsers, test cases and servers. This magic depends on keeping the skeleton small, on calling the subclass only at documented moments and, in Python, on enforcing the skeleton explicitly when overriding it would be an error. Letting several objects communicate through a single coordinator, instead of referring to one another directly, is the purpose of the Mediator pattern, which is developed in a future article of this series.