Strategy and Factory in Python: A dict Registry Instead of an if-elif Ladder
Help Desk SLA hours depend on the plan: 72 on free, 4 on pro, 1 on enterprise for a high-priority ticket. Replace the if-elif ladder with a dict, then a @register decorator and a policy_for factory, add a startup plan in its own file, and meet the error you get when the registry module was never imported.
What you will learn
- See why an if-elif ladder on a type grows into a merge-conflict magnet
- Use a dict of functions, then a register decorator, as Strategy plus Factory
- Add a new plan in a new file without editing old code
- Avoid the forgot-to-import trap and know when a plain if is better
Before you start
- Python functions and classes
- SOLID in Python With Protocol and ABCs
Our Help Desk gets tickets from customers on three plans: free, pro and enterprise. Each plan promises a different reply time. A high-priority ticket gets 72 hours on free, 4 hours on pro and 1 hour on enterprise.
Think of a parcel desk. The clerk doesn't read a rulebook for every parcel. She reads the label and puts the parcel on the matching shelf. Same ticket, but the plan decides the deadline.
The if-elif ladder
Here's the version most of us write first, ladder.py:
def due_hours(plan, priority):
if plan == "free":
return 72
elif plan == "pro":
if priority == "high":
return 4
return 24
elif plan == "enterprise":
if priority == "high":
return 1
return 8
else:
raise ValueError(f"unknown plan: {plan}")
tickets = [("free", "high"), ("pro", "high"),
("enterprise", "low")]
for plan, prio in tickets:
print(plan, prio, due_hours(plan, prio))
free high 72
pro high 4
enterprise low 8
Python tests the plan one rung at a time. An enterprise ticket passes three tests before it gets its answer. For three plans that's fine. The catch: every new plan means opening this same function and adding another rung.
Why the ladder hurts
Sales adds a startup plan, then a nonprofit plan, then a custom one. The ladder grows, and the last plan always waits behind every test above it. Two developers adding two plans both edit the same function in the same file, and they get a merge conflict. The real problem is that one function knows about every plan, so every change touches it.
Strategy and Factory in one picture
The fix has two parts. First, one shared shape: a method called due_hours that takes a priority. Each plan gets its own small object with that method. That's the Strategy pattern: same method, different rule, swappable. Second, something has to pick the right strategy. A dictionary does it perfectly: give it "pro" and it hands you the pro policy. That's a Factory: name in, object out.
The smallest version: a dict of functions
def free(priority):
return 72
def pro(priority):
return 4 if priority == "high" else 24
def enterprise(priority):
return 1 if priority == "high" else 8
RULES = {"free": free, "pro": pro,
"enterprise": enterprise}
rule = RULES["pro"]
print(rule.__name__, rule("high"))
pro 4
In Python, a function is already a strategy. Notice there are no brackets after the names in RULES: we store the functions, we don't call them. One lookup and no ladder at all.
The registry
For a real app we want a little more. registry.py:
from typing import Protocol
class SlaPolicy(Protocol):
def due_hours(self, priority: str) -> int: ...
POLICIES: dict[str, type[SlaPolicy]] = {}
def register(plan: str):
def add(cls):
POLICIES[plan] = cls
return cls
return add
def policy_for(plan: str) -> SlaPolicy:
try:
cls = POLICIES[plan]
except KeyError:
known = ", ".join(sorted(POLICIES))
raise ValueError(
f"unknown plan {plan!r}; known: {known}"
) from None
return cls()
SlaPolicyis a Protocol, like in SOLID in Python. Any class with adue_hoursmethod fits.POLICIESstarts empty. It's the registry: plan name to class.register(plan)returns a small function,add. Whenaddgets a class, it writes one row and returns the class unchanged. Soregisteris a decorator that writes one row in the dict.policy_foris the factory. It looks up the class and returns a fresh object, so the caller gets an object, not a name.
Each plan registers itself
from registry import register
@register("free")
class FreePolicy:
def due_hours(self, priority):
return 72
@register("pro")
class ProPolicy:
def due_hours(self, priority):
return 4 if priority == "high" else 24
@register("enterprise")
class EnterprisePolicy:
def due_hours(self, priority):
return 1 if priority == "high" else 8
When Python reads FreePolicy, the "free" row lands in the dictionary, and the same for pro and enterprise. There's no if on the plan anywhere. The small if on priority now lives inside each policy, where it belongs.
The caller
import policies # noqa: F401 fills the registry
from registry import POLICIES, policy_for
print(sorted(POLICIES))
tickets = [("free", "high"), ("pro", "high"),
("enterprise", "low")]
for plan, prio in tickets:
policy = policy_for(plan)
print(plan, prio, policy.due_hours(prio))
['enterprise', 'free', 'pro']
free high 72
pro high 4
enterprise low 8
The first line imports policies, which runs the decorators and fills the dict. The three tickets give 72, 4 and 8, exactly what the ladder gave, and main.py never names a single policy class.
Adding a plan without touching old code
A new file, startup_plan.py:
import policies # noqa: F401
from registry import POLICIES, register, policy_for
@register("startup")
class StartupPolicy:
def due_hours(self, priority):
return 12 if priority == "high" else 48
print(sorted(POLICIES))
policy = policy_for("startup")
print(type(policy).__name__, policy.due_hours("high"))
['enterprise', 'free', 'pro', 'startup']
StartupPolicy 12
Not a single line changed in registry.py or policies.py. New plan, new class, old code untouched. That's the open/closed principle: open to extend, closed to edits.
Two errors worth knowing
Ask for a plan that doesn't exist (unknown_plan.py):
import policies # noqa: F401
from registry import policy_for
try:
policy_for("gold")
except ValueError as err:
print(err)
unknown plan 'gold'; known: enterprise, free, pro
A clear message that lists what's known. Now the trap that catches almost everyone, forgot_import.py:
from registry import policy_for
try:
policy_for("pro")
except ValueError as err:
print(err)
unknown plan 'pro'; known:
The known list is empty. The classes exist, but policies was never imported, so the decorators never ran and nothing was registered. Registration runs on import. Make sure the module with your policies is imported once, at startup.
When to keep the if
Not every if should become a registry.
| Situation | Use |
|---|---|
| Two or three cases that rarely change | A plain if: shorter, everything in one place |
| Cases keep growing, other teams add plugins, or a config file picks behaviour by name | A registry |
The registry costs something too: you depend on that import side effect, and reading the code takes one extra jump to find the right class.
Say it in an interview
"How would you remove a long if-elif chain that switches on a type?" Three steps: define one interface, which is the Strategy. Map names to classes in a dict, which is the Factory. Then a new type is a new file, which is open/closed. And add the trade-off: I'd keep the if when there are only two or three stable cases. That last line shows judgement.
The same dict registry shows up again for LLM providers in Adapter and Facade.
Recap
- An if-elif ladder grows with every plan, and every change touches one function.
- A strategy is a small object (or function) with the same method and its own rule.
- A registry is a dict from a name to a class;
policy_foris the factory. - The
@registerdecorator adds one row, and only when its module is imported. - Keep the plain
ifwhen the cases are few and stable.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Python Class Methods, Static Methods and Properties: What Each One Receives
Instance methods get self, class methods get cls, static methods get nothing. Then properties, setters and deleters, with small runnable files and their real output.
Python Classes and Objects: __init__, self and PEP 8 Names
A class is the blueprint and an object is what you build from it. Car, Student, Dog, Circle and BankAccount show what __init__ and self really do, how attribute lookup works, the missing self error, and PEP 8 names.
Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
A child class gets everything from its parent, Python walks up and stops at the first match, and super() reaches the parent. Then polymorphism: one call, a different method for each object, with Animal, Employee and Shape examples and their real output.
Python Multiple Inheritance, the MRO and Mixins
A class can have two parents or a whole chain of them, and one list puts them in order: the MRO. Read it, watch Python walk it, see super() follow it, and build JsonMixin and LogMixin for a User class.
