Python Design Patterns

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.

  • Advanced
  • 2 min read
  • 1 runnable example
What you'll learn
  • An algorithm skeleton in the base class
  • Overriding selected steps
  • Keeping the workflow order fixed
CsvPipeline().run()
  1. 1read()Shared step
  2. 2process()process CSV: overridden
  3. 3save()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.

From a recipe card to code
run()📇 The recipe card with fixed steps
"read", ..., "save"🔒 Steps that never change
self.process()✏️ The blank line each cook fills in
CsvPipeline🧑‍🍳 One cook's version of that step
The base class fixes the order; subclasses fill in one step.
In one sentence

The 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

  1. DataPipeline.run() fixes the order: read, process, save.
  2. process is marked with @abstractmethod, so every subclass must provide it.
  3. CsvPipeline overrides only process.
  4. 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

Run code →
main.py
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()))
Get a Run button for this example

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.

  1. Replace the sample domain while preserving the pattern structure.
  2. Compare the pattern with a simpler implementation and explain the tradeoff.
  3. Write tests for each participant before adding another implementation.
Run in the Python compiler →

Common mistakes

Overriding run in the subclass

Rewriting run duplicates the order and can break it.

Problem
class CsvPipeline(DataPipeline):
    def run(self):
        return ["process CSV", "save"]  # read was forgotten
Fix
class CsvPipeline(DataPipeline):
    def process(self):
        return "process CSV"

Finished this lesson?

Mark it as learned to track your progress.