BehavioralPythonverifiedVerified

Template Method Pattern in Python

Defines the skeleton of an algorithm in a base class, deferring certain steps to subclasses without changing the algorithm's overall structure.

How to Implement the Template Method Pattern in Python

1Step 1: Define the abstract template with hook methods

from abc import ABC, abstractmethod
import json


class DataMiner(ABC):
    def mine(self, source: str) -> list[str]:
        """Template method -- defines the algorithm skeleton."""
        raw = self.extract_data(source)
        parsed = self.parse_data(raw)
        filtered = self.filter_data(parsed)
        self.report_results(filtered)
        return filtered

    @abstractmethod
    def extract_data(self, source: str) -> str: ...

    @abstractmethod
    def parse_data(self, raw: str) -> list[str]: ...

    # Hook -- subclasses may override
    def filter_data(self, data: list[str]) -> list[str]:
        return data

    def report_results(self, data: list[str]) -> None:
        print(f"Mined {len(data)} records.")

2Step 2: Implement concrete miners that override steps

class CsvMiner(DataMiner):
    def extract_data(self, source: str) -> str:
        return f"CSV content of {source}"

    def parse_data(self, raw: str) -> list[str]:
        return [line for line in raw.split("\n") if line]


class JsonMiner(DataMiner):
    def extract_data(self, source: str) -> str:
        return '{"data": ["a", "b", "c"]}'

    def parse_data(self, raw: str) -> list[str]:
        return json.loads(raw)["data"]

    def filter_data(self, data: list[str]) -> list[str]:
        return [item for item in data if item != "b"]

3Step 3: Run the algorithm with different data sources

CsvMiner().mine("report.csv")
JsonMiner().mine("api/v1/data")

Template Method Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Template Method Pattern in the Real World

Consider a recipe for baking bread. The overall process—mix, knead, let rise, bake, cool—is fixed. But the specific flour blend, kneading technique, and baking temperature are decisions left to the baker. The cookbook provides the invariant sequence; individual bakers customize the steps that can vary without disrupting the overall process.