Template Method Pattern Implementation in Python
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Template Method Pattern runs in O(1) time and O(1) space, in Python as in every other language.
- ✓abc.ABC with abc.abstractmethod is the mechanism: a class inheriting ABCMeta cannot be instantiated while any abstract method is unimplemented, and the error is a TypeError at construction naming the missing methods.
- ✓Mark the template method with typing.final so a type checker rejects an override, since Python cannot prevent one at run time.
- ✓The Python trap: Everything is overridable and nothing is enforced at run time: a subclass may override the template method itself and reorder or skip steps, and Python will not object.
- ✓Every step is a normal attribute lookup and call through the method resolution order, so a template with five hooks costs five method calls per invocation, and in a hot loop that overhead is real relative to inlining the logic.
What Template Method Pattern actually is
Template Method Pattern in Python: what you actually reach for
Python implementation
from abc import ABC, abstractmethod
from typing import final
class Importer(ABC):
# __init_subclass__ moves the "missing step" error to IMPORT time,
# instead of waiting until someone constructs the class.
def __init_subclass__(cls, **kw):
super().__init_subclass__(**kw)
missing = [n for n in ("_read", "_transform") if not callable(getattr(cls, n, None))]
if missing and not getattr(cls, "__abstractmethods__", None):
raise TypeError(f"{cls.__name__} is missing {missing}")
@final # a type checker rejects an override; Python cannot
def run(self, path: str) -> int:
raw = self._read(path)
rows = self._transform(raw)
self._after(rows) # optional hook with a default
return len(rows)
@abstractmethod
def _read(self, path: str) -> str: ...
@abstractmethod
def _transform(self, raw: str) -> list[dict]: ...
def _after(self, rows: list[dict]) -> None:
return None # default no-op hook
class CsvImporter(Importer):
def _read(self, path: str) -> str: return open(path).read()
def _transform(self, raw: str) -> list[dict]:
return [{"line": line} for line in raw.splitlines()]Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Python-specific trap
Performance in Python, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Python type or library should I use for Template Method Pattern?
abc.ABC with abc.abstractmethod is the mechanism: a class inheriting ABCMeta cannot be instantiated while any abstract method is unimplemented, and the error is a TypeError at construction naming the missing methods. The template method is a concrete method on the base calling those abstract ones. __init_subclass__ offers a second enforcement point that runs at class definition time rather than at instantiation, which catches the mistake earlier. typing.final documents a method that must not be overridden and type checkers enforce it.
What is the most common Python mistake when implementing Template Method Pattern?
Everything is overridable and nothing is enforced at run time: a subclass may override the template method itself and reorder or skip steps, and Python will not object. The abstract-method check also only fires at INSTANTIATION, so a subclass missing a step imports cleanly and fails later, at the point of construction, which may be far from the definition and only on a code path that runs in production. __init_subclass__ moves that check to import time, which is where you want it.
How does Template Method Pattern actually perform in Python?
Every step is a normal attribute lookup and call through the method resolution order, so a template with five hooks costs five method calls per invocation, and in a hot loop that overhead is real relative to inlining the logic. The MRO lookup is cached per class in the type attribute cache and is fast after the first call. ABCMeta adds a small cost to isinstance checks against the abstract base, which matters only if such checks are frequent. Time complexity is O(1) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying full price for a tool, check the student deals on AI and developer tools listed on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.