SyntaxPilot
Courses/Python/Lesson 39
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Python · Lesson 39 of 40

Design patterns in Python

queued

These are the notes for Python episode 39. Real apps change every week, and code that is glued together breaks when it changes. Raju's notification function crashes when a new channel arrives, so you invent the Strategy pattern (a dict of functions with a registering decorator). Two Settings objects disagree about the delivery fee, so you invent the Singleton. A loyalty feature breaks place_order, so you invent the Observer (publish and subscribe). A new bank's API doesn't fit, so you invent the Adapter. Every program below ran for real (Python 3.13.18).

What is a design pattern?

Real-life example: a recipe. A dosa recipe isn't one dosa; it's a proven way to make any dosa. And one word like "tadka" tells every cook the whole method.

A design pattern is a named, proven solution to a design problem that keeps coming back. The names (from the 1994 "Gang of Four" book) let developers talk fast: "use an observer here". Many patterns were written for languages like Java and C++; in Python, with functions as values, decorators and modules, they're often just a few lines.

The if/elif trap

def notify(channel, user, text):
    if channel == "sms":
        print(f"SMS to {user}: {text}")
    elif channel == "email":
        print(f"Email to {user}: {text}")
    elif channel == "whatsapp":
        print(f"WhatsApp to {user}: {text}")
    else:
        raise ValueError(f"unknown channel: {channel}")

notify("sms", "Asha", "Order picked up")
notify("email", "Asha", "Your bill: Rs 240")
notify("push", "Asha", "Rider is 2 min away")

Output:

SMS to Asha: Order picked up
Email to Asha: Your bill: Rs 240
Traceback (most recent call last):
  File "main.py", line 13, in <module>
    notify("push", "Asha", "Rider is 2 min away")
    ~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "main.py", line 9, in notify
    raise ValueError(f"unknown channel: {channel}")
ValueError: unknown channel: push

The mobile team calls notify("push", ...) and gets ValueError: unknown channel: push. Every new channel means editing the same function, and the code that chooses is glued to the code that does the work.

Strategy: a dict of functions

Real-life example: a chai stall's menu card maps each item's name to how to make it. "One masala chai" → pick that recipe, make it. A new item is one more line on the card.

The Strategy pattern: several interchangeable ways to do a job, chosen at run time. In Python each strategy is just a function, and the "menu card" is a dict. A small decorator (episode 25) registers each function — a registry, or plug-in system:

SENDERS = {}                         # channel name -> function

def channel(name):                   # a decorator that registers
    def register(fn):
        SENDERS[name] = fn
        return fn
    return register

@channel("sms")
def sms(user, text):
    print(f"SMS to {user}: {text}")

@channel("push")                     # new channel: no if/elif to edit
def push(user, text):
    print(f"Push to {user}: {text}")

def notify(name, user, text):
    send = SENDERS.get(name)
    if send is None:
        print("no such channel:", name, "| try", sorted(SENDERS))
        return
    send(user, text)

notify("sms", "Asha", "Order picked up")
notify("push", "Asha", "Rider is 2 min away")
notify("pigeon", "Asha", "Hi")

Output:

SMS to Asha: Order picked up
Push to Asha: Rider is 2 min away
no such channel: pigeon | try ['push', 'sms']
  • channel("sms") returns register, which stores the function in SENDERS and returns it unchanged.
  • Adding push needed no edit to notify. Unknown names get a helpful message instead of a crash.
  • This is the open/closed principle: open for extension, closed for editing.

The same idea with classes (closer to the Java version), for when a strategy needs its own data:

class Percent:
    def __init__(self, p): self.p = p
    def apply(self, amount): return amount * (100 - self.p) // 100

class Flat:
    def __init__(self, off): self.off = off
    def apply(self, amount): return max(0, amount - self.off)

def bill(amount, discount):
    return discount.apply(amount)       # any object with apply() works

print(bill(400, Percent(10)), bill(400, Flat(50)))

Output:

360 350

Singleton: exactly one object

class Settings:
    def __init__(self):
        self.delivery_fee = 30

checkout = Settings()
billing = Settings()
checkout.delivery_fee = 0            # free delivery today!
print(checkout.delivery_fee, billing.delivery_fee)
print(checkout is billing)

Output:

0 30
False

Every Settings() call makes a new object, so checkout and billing disagree: free delivery on one screen, ₹30 on the bill. For app-wide rules we want exactly one object — like one rule board in an office. That's a Singleton.

Python creates an object in two steps: __new__ creates it, then __init__ fills it in. Override __new__ to return the same object every time:

class Settings:
    _instance = None
    def __new__(cls):                # runs BEFORE __init__
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance.delivery_fee = 30
        return cls._instance         # always the same object

checkout = Settings()
billing = Settings()
checkout.delivery_fee = 0
print(checkout.delivery_fee, billing.delivery_fee)
print(checkout is billing)

Output:

0 0
True

The Pythonic singleton: a module

A module runs once; every import gets the same module object. So most Python projects simply write:

# settings.py
delivery_fee = 30
# checkout.py
import settings
settings.delivery_fee = 0     # billing.py sees 0 too

Use singletons sparingly: shared state everywhere makes code harder to test.

Observer: publish and subscribe

def tell_kitchen(order):  print("Kitchen: cook", order)
def tell_rider(order):    print("Rider: pick up", order)
def send_sms(order):      print("SMS: order", order, "confirmed")

def place_order(order):
    print("Order placed:", order)
    tell_kitchen(order)
    tell_rider(order)
    send_sms(order)
    add_points(order)                # the new loyalty feature

place_order("Masala Dosa")

Output:

Order placed: Masala Dosa
Kitchen: cook Masala Dosa
Rider: pick up Masala Dosa
SMS: order Masala Dosa confirmed
Traceback (most recent call last):
  File "main.py", line 12, in <module>
    place_order("Masala Dosa")
    ~~~~~~~~~~~^^^^^^^^^^^^^^^
  File "main.py", line 10, in place_order
    add_points(order)                # the new loyalty feature
    ^^^^^^^^^^
NameError: name 'add_points' is not defined

place_order has to know every reaction to an order. The loyalty team added one line, forgot an import, and the most important function now crashes with NameError.

Real-life example: a WhatsApp group. Post once; every member gets it; the poster doesn't need to know who's in the group; a new member just joins.

The Observer pattern (publish/subscribe): an event keeps a list of listener functions; subscribe adds one, publish calls them all.

class Event:
    def __init__(self):
        self.listeners = []
    def subscribe(self, fn):
        self.listeners.append(fn)
        return fn                    # so it works as a decorator
    def publish(self, *args):
        for fn in self.listeners:
            fn(*args)

order_placed = Event()

@order_placed.subscribe
def tell_kitchen(order): print("Kitchen: cook", order)

@order_placed.subscribe
def tell_rider(order):   print("Rider: pick up", order)

@order_placed.subscribe
def add_points(order):   print("Points: +10 for", order)

def place_order(order):
    print("Order placed:", order)
    order_placed.publish(order)      # doesn't know who is listening

place_order("Masala Dosa")

Output:

Order placed: Masala Dosa
Kitchen: cook Masala Dosa
Rider: pick up Masala Dosa
Points: +10 for Masala Dosa

subscribe returns the function, so it doubles as a decorator. place_order no longer knows who listens. Where you've seen it: a button's onclick handler, Django signals, game engines, message queues.

Add unsubscribe and you can remove listeners too:

class Event:
    def __init__(self): self.listeners = []
    def subscribe(self, fn): self.listeners.append(fn); return fn
    def unsubscribe(self, fn): self.listeners.remove(fn)
    def publish(self, *args):
        for fn in list(self.listeners):   # a copy, safe if a listener unsubscribes
            fn(*args)

ev = Event()
hi = ev.subscribe(lambda name: print("hi", name))
ev.publish("Asha")
ev.unsubscribe(hi)
ev.publish("Ravi")
print("listeners:", len(ev.listeners))

Output:

hi Asha
listeners: 0

Adapter: make it fit

Real-life example: a travel plug adapter. Your Indian charger and a UK socket both work; they just don't fit. The adapter fits both and changes neither.

class OldGateway:
    def pay(self, rupees):
        print(f"Paid Rs {rupees}")

class NewGateway:                    # a new bank: different method
    def make_payment(self, paise, currency):
        print(f"Charged {paise} paise ({currency})")

def checkout(gateway, amount):
    gateway.pay(amount)

checkout(OldGateway(), 240)
checkout(NewGateway(), 240)

Output:

Paid Rs 240
Traceback (most recent call last):
  File "main.py", line 13, in <module>
    checkout(NewGateway(), 240)
    ~~~~~~~~^^^^^^^^^^^^^^^^^^^
  File "main.py", line 10, in checkout
    gateway.pay(amount)
    ^^^^^^^^^^^
AttributeError: 'NewGateway' object has no attribute 'pay'

The new bank has make_payment(paise, currency); checkout calls pay(rupees). We can't edit the bank's code and don't want to edit every caller. The Adapter wraps the new object behind the interface we expect:

class OldGateway:
    def pay(self, rupees):
        print(f"Paid Rs {rupees}")

class NewGateway:
    def make_payment(self, paise, currency):
        print(f"Charged {paise} paise ({currency})")

class NewGatewayAdapter:             # looks like OldGateway outside
    def __init__(self, gateway):
        self.gateway = gateway
    def pay(self, rupees):
        self.gateway.make_payment(rupees * 100, "INR")

def checkout(gateway, amount):       # unchanged
    gateway.pay(amount)

checkout(OldGateway(), 240)
checkout(NewGatewayAdapter(NewGateway()), 240)

Output:

Paid Rs 240
Charged 24000 paise (INR)

checkout never checks the type, only that the object has pay. That's duck typing: "if it walks like a duck and quacks like a duck, it's a duck".

The pattern map

Pattern Problem The Python way
Strategy many ways to do one job, pick one at run time a dict of functions (+ a registry decorator)
Singleton something must exist exactly once a module; or __new__ returning one instance
Observer one event, many independent reactions subscribe / publish with a list of functions
Adapter two working pieces don't fit a wrapper class with the expected method
Decorator add behaviour around a function @decorator (episode 25)
Iterator walk any collection the same way __iter__ / __next__, generators (episode 24)
Context manager set up and always clean up with and __enter__ / __exit__ (episode 26)

Rule of thumb: reach for a pattern when the pain arrives, not before.

Common mistakes

Mistake What you see Why Fix
A growing if/elif per type ValueError: unknown channel: push every new case edits one function a dict of functions (strategy)
Settings() in every file 0 30 and False each call makes a new object a module, or __new__
place_order calls every listener NameError: name 'add_points' is not defined the sender must know every listener subscribe / publish
Calling a method the object doesn't have AttributeError: 'NewGateway' object has no attribute 'pay' two APIs don't fit an adapter class
SENDERS[name] for an unknown name KeyError: 'pigeon' the key isn't registered SENDERS.get(name) and a message
Patterns everywhere "just in case" 10 classes for a 20-line job no real pain to fix simple code first
SENDERS = {"sms": print}
SENDERS["pigeon"]("hi")

Output:

Traceback (most recent call last):
  File "main.py", line 2, in <module>
    SENDERS["pigeon"]("hi")
    ~~~~~~~^^^^^^^^^^
KeyError: 'pigeon'

Mini project: Raju's pluggable notifier

One file here (in a real project, settings.py, channels.py and events.py): a settings singleton, a channel registry, an order event, and an adapter for a legacy SMS class.

# --- settings (a singleton; in a real project: settings.py) ---
class Settings:
    _one = None
    def __new__(cls):
        if cls._one is None:
            cls._one = super().__new__(cls)
            cls._one.default_channel = "sms"
        return cls._one

# --- channels (strategy + registry) ---
SENDERS = {}
def channel(name):
    def register(fn):
        SENDERS[name] = fn
        return fn
    return register

@channel("email")
def email(user, text): print(f"  email -> {user}: {text}")

class LegacySMS:                          # old code we can't change
    def send_text(self, number, msg): print(f"  legacy sms -> {number}: {msg}")

class SMSAdapter:                         # adapter: looks like a sender function
    def __init__(self, legacy, phonebook): self.legacy, self.phonebook = legacy, phonebook
    def __call__(self, user, text): self.legacy.send_text(self.phonebook[user], text)

SENDERS["sms"] = SMSAdapter(LegacySMS(), {"Asha": "98xxxx1234"})

def notify(user, text, name=None):
    name = name or Settings().default_channel
    send = SENDERS.get(name)
    if send is None:
        print(f"  no channel {name!r}; have {sorted(SENDERS)}")
    else:
        send(user, text)

# --- events (observer) ---
class Event:
    def __init__(self): self.listeners = []
    def subscribe(self, fn): self.listeners.append(fn); return fn
    def publish(self, *args):
        for fn in self.listeners: fn(*args)

order_placed = Event()

@order_placed.subscribe
def kitchen(user, dish): print(f"  kitchen: cook {dish}")

@order_placed.subscribe
def tell_customer(user, dish): notify(user, f"{dish} confirmed")

def place_order(user, dish):
    print(f"order: {user} - {dish}")
    order_placed.publish(user, dish)

place_order("Asha", "Masala Dosa")

# a NEW channel, added without editing any line above:
@channel("push")
def push(user, text): print(f"  push -> {user}: {text}")

Settings().default_channel = "push"
place_order("Asha", "Filter Coffee")
notify("Asha", "hello", "pigeon")

Output:

order: Asha - Masala Dosa
  kitchen: cook Masala Dosa
  legacy sms -> 98xxxx1234: Masala Dosa confirmed
order: Asha - Filter Coffee
  kitchen: cook Filter Coffee
  push -> Asha: Filter Coffee confirmed
  no channel 'pigeon'; have ['email', 'push', 'sms']

Practice

  1. Add an "email" channel to the registry from the video, and make notify fall back to "sms" when the name is unknown.
Solution
SENDERS = {}
def channel(name):
    def register(fn):
        SENDERS[name] = fn
        return fn
    return register

@channel("sms")
def sms(user, text): print(f"SMS to {user}: {text}")

@channel("email")
def email(user, text): print(f"Email to {user}: {text}")

def notify(name, user, text):
    SENDERS.get(name, SENDERS["sms"])(user, text)

notify("email", "Asha", "Your bill: Rs 240")
notify("pigeon", "Asha", "Order picked up")

Output:

Email to Asha: Your bill: Rs 240
SMS to Asha: Order picked up
  1. Write an adapter for a gateway whose method is pay_in_dollars(dollars) (assume ₹83 = $1), so checkout(gateway, rupees) works unchanged.
Solution
class DollarGateway:
    def pay_in_dollars(self, dollars):
        print(f"Paid ${dollars:.2f}")

class DollarAdapter:
    RATE = 83
    def __init__(self, gateway): self.gateway = gateway
    def pay(self, rupees): self.gateway.pay_in_dollars(rupees / self.RATE)

def checkout(gateway, amount):
    gateway.pay(amount)

checkout(DollarAdapter(DollarGateway()), 830)

Output:

Paid $10.00
  1. Make the Observer's publish keep going even if one listener crashes, and report the error.
Solution
class Event:
    def __init__(self): self.listeners = []
    def subscribe(self, fn): self.listeners.append(fn); return fn
    def publish(self, *args):
        for fn in self.listeners:
            try:
                fn(*args)
            except Exception as e:
                print(f"listener {fn.__name__} failed: {e!r}")

ev = Event()

@ev.subscribe
def broken(order): add_points(order)

@ev.subscribe
def kitchen(order): print("Kitchen: cook", order)

ev.publish("Masala Dosa")

Output:

listener broken failed: NameError("name 'add_points' is not defined")
Kitchen: cook Masala Dosa

Quick quiz

class Box:
    _one = None
    def __new__(cls):
        if cls._one is None:
            cls._one = super().__new__(cls)
        return cls._one

a, b = Box(), Box()
a.size = 5
print(b.size, a is b)

Options: 5 True · AttributeError · None False · 5 False

Answer

5 True. __new__ returns the same object both times, so a and b are one object.

Interview questions

  1. What is a design pattern? A named, reusable solution to a common design problem — a template, not finished code.
  2. How is Strategy usually done in Python? With first-class functions in a dict (or objects sharing one method), chosen at run time.
  3. __new__ vs __init__? __new__ creates and returns the object (it receives the class); __init__ initialises an object that already exists.
  4. Why is a module often a better singleton than a class? Python imports a module once and caches it in sys.modules, so every import gets the same object, with no extra code.
  5. What problem does Observer solve? It decouples the code that raises an event from the code that reacts, so reactions can be added or removed without editing the sender.
  6. Adapter vs Decorator? An adapter changes an interface so it fits; a decorator keeps the interface and adds behaviour.
  7. What is duck typing? Using an object for what it can do (its methods), not for its type: anything with pay() can pay.
  8. What is the open/closed principle? Code should be open for extension (new features) but closed for modification (no editing old, tested code).

Glossary

Term Meaning Example
Design pattern A named, proven solution to a common design problem Strategy, Observer
Strategy pattern Interchangeable ways to do a job, chosen at run time SENDERS[name](user, text)
Registry A dict where features register themselves by name SENDERS = {}
Plug-in A feature added by registering, without editing the core @channel("push")
First-class function A function used as a value: stored, passed, returned SENDERS["sms"] = sms
Decorator A function that wraps or registers another function @channel("sms")
Open/closed principle Open for extension, closed for modification add push without editing notify
Singleton A class with exactly one instance Settings() always the same object
Instance One object made from a class checkout = Settings()
__new__ The dunder method that creates the object, before __init__ return cls._instance
__init__ The dunder method that fills in a new object self.delivery_fee = 30
is True when two names point at the same object checkout is billing
Module A .py file; imported once and shared import settings
Observer pattern Listeners subscribe to an event; the publisher calls them all order_placed.publish(order)
Publish / subscribe Announce an event / register to hear it subscribe(fn), publish(...)
Listener A function called when an event is published tell_kitchen
Coupling How much one piece of code depends on another place_order calling everyone
Adapter pattern A wrapper that makes one interface look like another NewGatewayAdapter.pay()
Interface The methods code expects an object to have pay(rupees)
Duck typing Use an object by what it can do, not its type anything with pay()
Wrapper An object that holds another and forwards calls to it self.gateway.make_payment(...)
ValueError Raised when a value is the right type but not allowed unknown channel: push
NameError A name is used that was never defined or imported add_points
AttributeError An object has no attribute or method with that name 'NewGateway' object has no attribute 'pay'

Summary

  • A pattern is a named fix for a problem that keeps coming back; use one when the pain arrives.
  • Strategy: a dict of functions, filled by a registry decorator — add features without editing.
  • Singleton: one shared object via __new__, or simply a module.
  • Observer: subscribe / publish, so the sender doesn't know its listeners.
  • Adapter: wrap what doesn't fit, and let duck typing do the rest.
  • Next episode: the capstone — a complete command-line app, end to end.