Template Method Pattern in Python
Fix the order of an algorithm's steps in a base class and let subclasses fill in the steps that change.
- An algorithm skeleton in the base class
- Overriding selected steps
- Keeping the workflow order fixed
- 1
read()Shared step - 2
process()process CSV: overridden - 3
save()Shared step
Fixed steps, customizable parts
The problem
Many processes share the same order of steps but differ in one step: every data pipeline reads, processes and saves, but processing CSV differs from processing JSON. Copying the whole process for each variant duplicates the order and invites mistakes.
Think of it like this
The Template Method pattern is like a recipe card with one blank line. The card fixes the order: prepare, cook the filling, serve. Each cook only fills in the blank line with their own filling; nobody can change the order of the steps.
run()📇 The recipe card with fixed steps"read", ..., "save"🔒 Steps that never changeself.process()✏️ The blank line each cook fills inCsvPipeline🧑🍳 One cook's version of that stepThe Template Method pattern defines the steps of an algorithm in a base class method and lets subclasses override specific steps without changing the overall order.
Key points
DataPipeline.run()fixes the order: read, process, save.processis marked with@abstractmethod, so every subclass must provide it.CsvPipelineoverrides onlyprocess.CsvPipeline().run()keeps the fixed order and uses the CSV step.
When should you use it?
- Workflows with a fixed order and a few varying steps: pipelines, exports, game turns.
- Frameworks that call your code at defined points.
- Removing duplicated control flow from similar classes.
When not to use it
- Only one step varies and it is simple: pass a function in (Strategy) instead of subclassing.
- The steps themselves change order between variants.
Example code
from abc import ABC, abstractmethod
class DataPipeline(ABC):
# Template Method: fix the workflow and customize selected steps.
def run(self):
# Keep the algorithm order stable.
return ["read", self.process(), "save"]
@abstractmethod
def process(self): pass
class CsvPipeline(DataPipeline):
def process(self): return "process CSV"
print(" -> ".join(CsvPipeline().run()))
Result of running the code
read -> process CSV -> save
Code explanation
run() in DataPipeline returns the three steps in a fixed order and calls self.process() for the middle one. process is an abstract method, so Python refuses to create a subclass object that does not implement it. CsvPipeline provides process, and run() combines it with the fixed steps, producing read -> process CSV -> save.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Replace the sample domain while preserving the pattern structure.
- Compare the pattern with a simpler implementation and explain the tradeoff.
- Write tests for each participant before adding another implementation.
Common mistakes
Overriding run in the subclass
Rewriting run duplicates the order and can break it.
class CsvPipeline(DataPipeline):
def run(self):
return ["process CSV", "save"] # read was forgotten
class CsvPipeline(DataPipeline):
def process(self):
return "process CSV"
Finished this lesson?
Mark it as learned to track your progress.