Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Python
  • Python for AI: The Five Tools You Actually Need
  • Thinking Like a Python Architect in an AI-First World
  • Your First Python Program: print, Comments, sep and end
  • Set Up PyCharm for Python: Install, First Project and First Run
  • Run a Python File and Read the Error: Tracebacks in Three Steps
  • Python Data Types, Variables and Strings: Indexing, Slicing and f-strings
  • Python Operators: Arithmetic, Comparison, Logical, Membership, Identity and Precedence
  • Python Conditionals and Loops: if/elif/else, for, while, break and continue
  • Looping Over Real Data in Python: Dicts, Lists of Dicts, enumerate and zip
  • Checking AI-Written Python Code: A Six-Step Habit That Finds Three Hidden Faults
  • Python Basics Practice: Report Card, Shopping Cart and Password Checker from a Prompt
  • Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs
  • Type Hints on Python Functions: Parameters, Returns, None and Collections
  • Python lambda, map, filter, Modules and Packages (with pip and venv)
  • What @ Means in Python: Decorators Built by Hand, Then Shortened
  • Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package
  • Python Lists, Tuples, Sets and Dicts, Plus Type Hints on Variables
  • Python Comprehensions: List, Dict, Set and Generator Expressions, Read as Loops
  • Python Class Methods, Static Methods and Properties: What Each One Receives
  • Python Classes and Objects: __init__, self and PEP 8 Names
  • Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
  • Python Multiple Inheritance, the MRO and Mixins
  • Python Encapsulation and Special Methods: Underscores, __str__, __add__ and __len__
  • Python Composition, Abstract Classes and Dataclasses
  • Python OOP Practice: Design a Bank, an Employee System and a Library
  • SOLID in Python With Protocol and ABCs: Five Small Refactors of One Bloated Ticket Service
  • Strategy and Factory in Python: A dict Registry Instead of an if-elif Ladder
  • Adapter and Facade in Python: One Interface Over Three LLM Providers
  • Entities, Value Objects and Aggregates: One Root Guards the Rules, One Transaction Saves One Aggregate
  • Python Decorators vs the Decorator Pattern vs Proxy: Same Shape, Different Job
  • Set Up a Python AI Project with uv, VS Code and an API Key in .env
  • uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
  • Python try and except Basics: Catch an Error and Keep Going
  • Read and Write a File in Python: open, with, Modes and Encoding
  • Python Custom Exceptions and Advanced Error Handling: raise, raise from and the Call Stack
  • Python Logging and Debugging: Levels, Handlers, logger.exception and breakpoint()
  • Python File Modes, pathlib and Context Managers: x, r+, rb, Path and __enter__/__exit__
  • Python CSV, JSON and Large Files: csv, json, yield Pipelines, tomllib and pickle
  • Python Practice: Build a Log File Analyzer and a File Organizer
  • Python Project Structure for AI-Assisted Development: Packages, config.py and AGENTS.md
  • Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
  • Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
  • Async Python: async def, await, asyncio.gather and the Blocking Trap
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Getting Started with Flask: Routes, Jinja2 Templates and WSGI in One Small App
  • Your First Flask App with uv: From an Empty Folder to a Page in Debug Mode
  • Flask Routes, Templates and url_for: Converters, Forms, Redirects and the Signed Session
  • Flask-SQLAlchemy Models and Flask-Migrate: From a Python Class to a Real Table
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a Flask Blog: The App Factory, Blueprints, the Instance Folder and CORS Done Right
  • How a Request and a Login Flow Through a Flask Blog: Flask-Login, CSRF and the Signed Session
  • Testing a Flask Blog with pytest: A Test App from the Factory, Fixtures and the Test Client
  • Python Decorators vs the Decorator Pattern vs Proxy: Same Shape, Different Job
  • Repository and Unit of Work With SQLAlchemy: Both Writes or Neither, and a Test With No Database
  • Dependency Injection With FastAPI Depends: Providers, dependency_overrides and yield
  1. Blog
  2. /
  3. Python
  4. /
  5. Object-Oriented Python

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.

Chaand Sheikh

·27 November 2026·Updated 29 November 2026Object-Oriented Python

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

Name in, strategy object out "pro" policy_for() factory POLICIES "free" : FreePolicy "pro" : ProPolicy "enterprise" : EnterprisePolicy ProPolicy() due_hours("high") = 4
Each policy is a strategy. The dict lookup is the factory.

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()
  • SlaPolicy is a Protocol, like in SOLID in Python. Any class with a due_hours method fits.
  • POLICIES starts empty. It's the registry: plan name to class.
  • register(plan) returns a small function, add. When add gets a class, it writes one row and returns the class unchanged. So register is a decorator that writes one row in the dict.
  • policy_for is 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.

SituationUse
Two or three cases that rarely changeA plain if: shorter, everything in one place
Cases keep growing, other teams add plugins, or a config file picks behaviour by nameA 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_for is the factory.
  • The @register decorator adds one row, and only when its module is imported.
  • Keep the plain if when the cases are few and stable.

Keep going in Python · 27 of 57

Previous
SOLID in Python With Protocol and ABCs: Five Small Refactors of One Bloated Ticket Service
Next post
Adapter and Facade in Python: One Interface Over Three LLM Providers
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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.

On this page

  • The if-elif ladder
  • Why the ladder hurts
  • Strategy and Factory in one picture
  • The smallest version: a dict of functions
  • The registry
  • Each plan registers itself
  • The caller
  • Adding a plan without touching old code
  • Two errors worth knowing
  • When to keep the if
  • Say it in an interview
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.