Strategy 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
- ✓Strategy Pattern runs in O(1) time and O(1) space, in Python as in every other language.
- ✓A function is the strategy; no interface is required. typing.Protocol describes the call signature structurally so a type checker verifies it without any runtime base class, and collections.abc.Callable is the runtime check.
- ✓Pass the function, do not wrap it in a class with a single execute method; a reviewer will delete the class.
- ✓The Python trap: Assigning a function to a CLASS attribute turns it into a method, because functions are descriptors: self is silently passed as the first argument and your strategy receives an extra parameter it did not declare.
- ✓Every strategy call is a full Python function call with frame construction, which is roughly a hundred nanoseconds and dwarfs the work in a trivial strategy.
What Strategy Pattern actually is
Strategy Pattern in Python: what you actually reach for
Python implementation
from typing import Protocol
from operator import itemgetter
from functools import partial
class Pricing(Protocol):
def __call__(self, cents: int) -> int: ...
def flat(cents: int, *, off: int) -> int: return max(0, cents - off)
def percent(cents: int, *, pct: int) -> int: return cents * (100 - pct) // 100
class Cart:
def __init__(self, pricing: Pricing):
self.pricing = pricing # INSTANCE attribute: no descriptor binding
def total(self, cents: int) -> int: return self.pricing(cents)
Cart(partial(percent, pct=10)).total(1000) # 900
class Broken:
pricing = flat # CLASS attribute: becomes a METHOD, gets self
# Late binding: without pct=p these would all read the LAST p.
strategies = [partial(percent, pct=p) for p in (5, 10, 20)]
rows = sorted([{"c": 3}, {"c": 1}], key=itemgetter("c")) # C-speed keyThink 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 Strategy Pattern?
A function is the strategy; no interface is required. typing.Protocol describes the call signature structurally so a type checker verifies it without any runtime base class, and collections.abc.Callable is the runtime check. functools.partial pre-binds arguments to build a specialised strategy from a general one, and operator supplies ready-made ones such as operator.itemgetter and operator.attrgetter, which are the idiomatic key= strategies for sorted and for heapq.
What is the most common Python mistake when implementing Strategy Pattern?
Assigning a function to a CLASS attribute turns it into a method, because functions are descriptors: self is silently passed as the first argument and your strategy receives an extra parameter it did not declare. Assigning the same function to an INSTANCE attribute does not, because instance attribute lookup skips the descriptor protocol. This asymmetry catches almost everyone once. Wrap the class-level one in staticmethod to opt out. The second trap is the late-binding closure: strategies built in a loop from a lambda that reads the loop variable all see its final value unless you bind it with a default argument.
How does Strategy Pattern actually perform in Python?
Every strategy call is a full Python function call with frame construction, which is roughly a hundred nanoseconds and dwarfs the work in a trivial strategy. That is why key= functions dominate the cost of sorting small records and why the C-implemented itemgetter is worth reaching for. functools.partial is cheaper than a wrapping lambda because it is a C object that splices arguments without creating a Python frame. Since Python 3.11 the specialising interpreter removes some of the per-call overhead for stable call sites, but a strategy called through a variable still costs a real call. 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 trialIf you are a student, see what GitHub Copilot offers students for free 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.