Design Patterns in Python

Published by Brayan K

Master the essential design patterns used in professional Python development. Learn Singleton, Factory, and Strategy patterns with real-world examples and best practices.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Patterns you have already used

A design pattern is a name for a solution that keeps coming back. This lesson takes the three in its title and shows the Python way to write each one. Python passes functions and classes around like any other value, so its versions are often a function or a dictionary where the classic versions need a family of classes.

Some of it isn't new. Passing a function in, as Higher-Order Functions & Function Factories did, is the Strategy pattern. Its dictionary of functions, like the registering decorator in Decorators & Advanced Features, is the tool this lesson's factories are built with. How to lay out a whole application is in Architecture Patterns for Python Apps (MVC, Clean Architecture).

Singleton: one shared object, made by a module

A singleton provides one shared instance within a defined scope. For settings in one Python process, a module-level object is often enough; that convention does not prevent someone from constructing another Settings object. Modules and Packages showed that ordinary imports reuse the module cached under its name. Its top-level object is shared by those importers in that process; reloading or loading the file under another name is outside that guarantee:

from pathlib import Path

Path("settings.py").write_text('''print("settings.py runs")

class Settings:
    def __init__(self):
        self.currency = "GBP"
        self.vat = 0.2

settings = Settings()
''', encoding="utf-8")
Path("shop.py").write_text('''from settings import settings

def price(amount):
    return f"{amount * (1 + settings.vat):.2f} {settings.currency}"
''', encoding="utf-8")
Path("admin.py").write_text('''from settings import settings

def cut_vat(rate):
    settings.vat = rate
''', encoding="utf-8")

import shop
import admin

print(shop.price(10))
admin.cut_vat(0.05)
print(shop.price(10))
print(shop.settings is admin.settings)

# ✅ Expected output:
# settings.py runs
# 12.00 GBP
# 10.50 GBP
# True

settings.py runs appears once, though two files import it, and the VAT that admin.py changed is the VAT shop.py uses. The trap is replacing the object instead of changing it. A name taken with from keeps the old object, as Modules and Packages showed for any name:

from pathlib import Path

Path("settings.py").write_text('''class Settings:
    def __init__(self, vat):
        self.vat = vat

settings = Settings(0.2)
''', encoding="utf-8")

import settings as config
from settings import settings

config.settings = config.Settings(0.2)
config.settings.vat = 0.05
print(settings.vat, config.settings.vat)
print(settings is config.settings)

# ✅ Expected output:
# 0.2 0.05
# False

With these from-imports, mutating the shared object is visible to both callers. If replacement is part of your design, have callers read config.settings through the module each time instead of retaining the earlier binding.

The __new__ singleton runs __init__ every time

The version in many pattern books makes the class refuse a second object. As Magic Methods & the Python Data Model showed, __new__ makes the object and __init__ fills it in, so the usual way is a __new__ that hands back the same object every time. But Python calls __init__ on whatever __new__ returns, so __init__ runs on every call, and here it empties the list each time:

class Logger:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self):
        print("__init__ runs")
        self.lines = []

    def log(self, message):
        self.lines.append(message)

Logger().log("started")
Logger().log("saved")
print(Logger().lines)

# ✅ Expected output:
# __init__ runs
# __init__ runs
# __init__ runs
# []

A flag that keeps __init__ from running twice only turns that into arguments that are silently ignored. debug=True does nothing here:

class AppConfig:
    _instance = None

    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self, debug=False):
        if not hasattr(self, "_initialised"):
            self.debug = debug
            self._initialised = True

live = AppConfig(debug=False)
test = AppConfig(debug=True)
print(test.debug, test is live)

# ✅ Expected output:
# False True

And a base class that keeps one object for all its subclasses gives out the wrong one when the base is made first. Python doesn't run AppConfig's __init__ on it, since it isn't an AppConfig:

class Singleton:
    _instance = None

    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

class AppConfig(Singleton):
    def __init__(self, debug=False):
        self.debug = debug

plain = Singleton()
config = AppConfig(debug=True)
print(type(config).__name__)
print(config.debug)

# ✅ Expected output:
# Singleton

# ✅ Expected error:
# AttributeError: 'Singleton' object has no attribute 'debug'

mypy 1.19.1 reports no issues for such a class, hints and all, so nothing warns you that __init__ runs again.

A @singleton decorator turns the class into a function

Another common version is a decorator like the ones in Decorators & Advanced Features. It returns a function that makes the object on the first call and keeps it, and that function takes over the class's name, so the class itself is gone:

def singleton(cls):
    instances = {}

    def get_instance(*args, **kwargs):
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]

    return get_instance

@singleton
class Logger:
    def __init__(self):
        self.lines = []

log = Logger()
print(Logger() is log)
print(type(Logger).__name__, Logger.__name__)
print(isinstance(log, Logger))

# ✅ Expected output:
# True
# function get_instance

# ✅ Expected error:
# TypeError: isinstance() arg 2 must be a type, a tuple of types, or a union

A subclass fails too: class FileLogger(Logger) stops with TypeError: function() argument 'code' must be code, not str, since a function can't be a parent class. mypy 1.19.1 reports nothing for either line.

When the object should only be made the first time it's needed, cache a function that makes it. functools.cache is the lru_cache(maxsize=None) that Decorators & Advanced Features showed:

import functools

class Settings:
    def __init__(self):
        print("making the settings")
        self.vat = 0.2

@functools.cache
def get_settings():
    return Settings()

print("program starts")
print(get_settings() is get_settings())
print(get_settings().vat)

# ✅ Expected output:
# program starts
# making the settings
# True
# 0.2

A cached factory is not an exactly-once initialization lock: concurrent first calls can run it more than once, and clearing its cache permits another creation. The calls above are sequential. The standard library also provides named shared objects for loggers: logging.getLogger("shop") returns the same logger every time it's given "shop", and another one for "admin". Logging, Debugging & Error Handling at Scale covers loggers.

A shared object is shared by your tests too

Whatever one part of a program leaves in a shared object, the next part finds. Tests show it first: here the second test fails only because the first one ran.

class Cart:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance.items = []
        return cls._instance

def test_add_tea():
    cart = Cart()
    cart.items.append("tea")
    return cart.items == ["tea"]

def test_starts_empty():
    return Cart().items == []

print(test_add_tea())
print(test_starts_empty())

# ✅ Expected output:
# True
# False

Pass the object in, instead of having the code fetch the shared one, and each test can make its own:

class Cart:
    def __init__(self):
        self.items = []

def add_item(cart, item):
    cart.items.append(item)
    return len(cart.items)

def test_add_tea():
    cart = Cart()
    return add_item(cart, "tea") == 1

def test_starts_empty():
    return Cart().items == []

print(test_add_tea())
print(test_starts_empty())

# ✅ Expected output:
# True
# True

Handing a part what it needs, rather than letting it fetch a shared object, is called dependency injection. Architecture Patterns for Python Apps builds on it, and Testing with pytest: Fixtures, Parametrisation & Mocks gives each test a fresh object without you writing that by hand.

Factory: every class is one, and a dictionary picks which

A factory is anything you call to get a new object, so every class is one already: Card() makes a card payment. When the class depends on data, such as a name typed into a form, keep the classes in a dictionary and call the one the name picks. Check the name first, and the error says what went wrong:

class Card:
    def pay(self, amount):
        return f"card charged {amount:.2f}"

class PayPal:
    def pay(self, amount):
        return f"PayPal charged {amount:.2f}"

PAYMENTS = {"card": Card, "paypal": PayPal}

def make_payment(kind):
    if kind not in PAYMENTS:
        raise ValueError(f"unknown payment {kind!r}; choose from {sorted(PAYMENTS)}")
    return PAYMENTS[kind]()

print(make_payment("paypal").pay(12.5))
print(make_payment("card").pay(3))
make_payment("bitcoin")

# ✅ Expected output:
# PayPal charged 12.50
# card charged 3.00

# ✅ Expected error:
# ValueError: unknown payment 'bitcoin'; choose from ['card', 'paypal']

The dictionary holds the classes themselves, with no brackets. With brackets it holds objects: they are all made when the dictionary is, and every lookup returns the same one. That's the slip Higher-Order Functions & Function Factories showed with functions:

class Card:
    def __init__(self):
        print("connecting to the card company")

class PayPal:
    def __init__(self):
        print("connecting to PayPal")

PAYMENTS = {"card": Card(), "paypal": PayPal()}
print("ready")
print(PAYMENTS["card"] is PAYMENTS["card"])

# ✅ Expected output:
# connecting to the card company
# connecting to PayPal
# ready
# True

The default_factory=list in Data Classes & Advanced Class Patterns was the same idea: something to call for a new object each time.

The pattern books' Factory Method has a subclass override a method to choose the class to make. Passing the class in does the same job, and a test can pass a fake:

class StripeClient:
    def charge(self, amount):
        return f"Stripe charged {amount:.2f}"

class FakeClient:
    def charge(self, amount):
        return f"test: would charge {amount:.2f}"

def take_payment(amount, make_client=StripeClient):
    client = make_client()
    return client.charge(amount)

print(take_payment(29.99))
print(take_payment(29.99, make_client=FakeClient))

# ✅ Expected output:
# Stripe charged 29.99
# test: would charge 29.99

The versions of these patterns built on abc, which make a subclass write certain methods, are in Abstract Base Classes (abc).

Two ways a factory goes wrong

An if/elif factory with no final else returns None for any name it doesn't know, and the error appears later, somewhere else:

class EmailSender:
    def send(self, to):
        return f"email to {to}"

class TextSender:
    def send(self, to):
        return f"text to {to}"

def make_sender(channel):
    if channel == "email":
        return EmailSender()
    elif channel == "text":
        return TextSender()

sender = make_sender("Email")
print(sender)
print(sender.send("[email protected]"))

# ✅ Expected output:
# None

# ✅ Expected error:
# AttributeError: 'NoneType' object has no attribute 'send'

A @classmethod constructor, like Temperature.from_fahrenheit() in Decorators & Advanced Features, is a factory on the class itself. Write cls(...) in it rather than the class's name, so a subclass gets objects of its own class:

class Money:
    def __init__(self, pence):
        self.pence = pence

    @classmethod
    def from_pounds(cls, pounds):
        return cls(round(pounds * 100))

    @classmethod
    def from_text(cls, text):
        return cls.from_pounds(float(text.removeprefix("£")))

    def __repr__(self):
        return f"{type(self).__name__}({self.pence})"

class Tip(Money):
    pass

print(Money(250), Money.from_pounds(2.5), Money.from_text("£2.50"))
print(Tip.from_pounds(1.5))

# ✅ Expected output:
# Money(250) Money(250) Money(250)
# Tip(150)

A @staticmethod that returns Money(...) instead makes a Money even when it's called as Tip.from_pounds(1.5).

Strategy: pass in the part that varies

Strategy means choosing how part of a job is done by passing that part in. In Python it's usually a function, as in Higher-Order Functions & Function Factories, and a default keeps the common case short, as key= does for sorted():

def no_discount(total):
    return total

def student(total):
    return total * 0.9

def checkout(total, discount=no_discount):
    return f"{discount(total):.2f}"

print(checkout(80))
print(checkout(80, student))
print(checkout(80, lambda total: total - 5))

# ✅ Expected output:
# 80.00
# 72.00
# 75.00

Every strategy must accept what the caller gives it. Inheritance and Polymorphism's rule that a child must accept what its parent accepts holds for functions too:

def student(total):
    return total * 0.9

def two_for_one(total, items):
    return total - total / items

def checkout(total, discount):
    return f"{discount(total):.2f}"

print(checkout(80, student))
print(checkout(80, two_for_one))

# ✅ Expected output:
# 72.00

# ✅ Expected error:
# TypeError: two_for_one() missing 1 required positional argument: 'items'

With the Callable hint from Type Hints & Static Typing with mypy, discount: Callable[[float], float], mypy 1.19.1 catches this before the program runs: Argument 2 to "checkout" has incompatible type "Callable[[float, int], float]"; expected "Callable[[float], float]".

A strategy with a setting, such as a percentage, is a function factory or a partial(), both from Higher-Order Functions & Function Factories:

from functools import partial

def percent_off(percent):
    def discount(total):
        return total * (100 - percent) / 100
    return discount

def percent_of(total, percent):
    return total * (100 - percent) / 100

def checkout(total, discount):
    return f"{discount(total):.2f}"

print(checkout(80, percent_off(10)))
print(checkout(80, partial(percent_of, percent=25)))

# ✅ Expected output:
# 72.00
# 60.00

When other code needs to read that setting, use a class whose objects can be called, with the __call__ from Magic Methods & the Python Data Model:

class PercentOff:
    def __init__(self, percent):
        self.percent = percent

    def __call__(self, total):
        return total * (100 - self.percent) / 100

def checkout(total, discount):
    return f"{discount(total):.2f}"

ten = PercentOff(10)
print(checkout(80, ten))
print(ten.percent)

# ✅ Expected output:
# 72.00
# 10

Name the method apply() instead of __call__, and checkout(80, PercentOff(10)) stops with TypeError: 'PercentOff' object is not callable.

Practice: shipping companies and their prices

A factory makes a shipper by name, and each shipper takes a pricing strategy. Fill in the default strategy, the key the dictionary is looked up with, and the strategy for the heavy parcel. If you get stuck, the comment on each blank's line gives it away.

class Standard:
    def __init__(self, pricing):
        self.pricing = pricing

    def quote(self, kg):
        return f"standard {self.pricing(kg):.2f}"

class Express:
    def __init__(self, pricing):
        self.pricing = pricing

    def quote(self, kg):
        return f"express {self.pricing(kg) + 5:.2f}"

def flat(kg):
    return 4.99

def by_weight(kg):
    return 2.5 + kg * 0.75

SHIPPERS = {"standard": Standard, "express": Express}

def make_shipper(name, pricing=___):           # 👉 replace ___ with flat
    if name not in SHIPPERS:
        raise ValueError(f"no shipper called {name!r}")
    return SHIPPERS[___](pricing)              # 👉 replace ___ with name

heavy = make_shipper("standard", ___)          # 👉 replace ___ with by_weight
print(make_shipper("standard").quote(4))
print(heavy.quote(4))
print(make_shipper("express", by_weight).quote(2))

# ✅ Expected output:
# standard 4.99
# standard 5.50
# express 9.00

Run it before filling the blanks, and it stops at the def line with NameError: name '___' is not defined: a default value is worked out when def runs, not when the function is called.

On your own: a basket with coupons

Write a class Basket whose @classmethod from_text() builds a basket from text like "tea 120, milk 90, cake 250", a dictionary of names and prices in pence. Its total() takes a discount strategy, with no_discount as the default, and returns the total after the discount. Write no_discount, percent_off(percent), which returns a discount function that rounds down to whole pence with //, and a dictionary COUPONS with "SAVE10" and "HALF". If COUPONS[code]() sneaks in, with brackets, Python stops at the first coupon, saying the discount function is missing an argument.

# your code here

basket = Basket.from_text("tea 120, milk 90, cake 250")
print(basket.items)
print(basket.total())
for code in ["SAVE10", "HALF", "FREE"]:
    if code in COUPONS:
        print(code, basket.total(COUPONS[code]))
    else:
        print(f"no coupon called {code!r}")
def no_discount(pence):
    return pence

def percent_off(percent):
    def discount(pence):
        return pence * (100 - percent) // 100
    return discount

COUPONS = {"SAVE10": percent_off(10), "HALF": percent_off(50)}

class Basket:
    def __init__(self, items):
        self.items = items

    @classmethod
    def from_text(cls, text):
        items = {}
        for part in text.split(","):
            name, pence = part.split()
            items[name] = int(pence)
        return cls(items)

    def total(self, discount=no_discount):
        return discount(sum(self.items.values()))

basket = Basket.from_text("tea 120, milk 90, cake 250")
print(basket.items)
print(basket.total())
for code in ["SAVE10", "HALF", "FREE"]:
    if code in COUPONS:
        print(code, basket.total(COUPONS[code]))
    else:
        print(f"no coupon called {code!r}")

# ✅ Expected output:
# {'tea': 120, 'milk': 90, 'cake': 250}
# 460
# SAVE10 414
# HALF 230
# no coupon called 'FREE'

part.split() with no argument splits on any run of spaces and ignores the space after each comma, so " milk 90" gives ["milk", "90"].

Practice quiz

Counter's __new__ always returns the one Counter it keeps, and its __init__ sets self.count = 0. After c = Counter(), then c.count += 5, then Counter(), what does print(c.count) print?

  • 5
  • 0
  • It stops with AttributeError
  • 6

Answer: 0. Counter() hands back the same object, and Python then runs __init__ on it again, which sets count back to 0.

settings.py holds settings = Settings(0.2), and Settings stores its argument as vat. The program runs import settings as config, then from settings import settings, then config.settings.vat = 0.05. What does print(settings.vat) print?

  • 0.2
  • It stops with ImportError
  • 0.05
  • It stops with AttributeError

Answer: 0.05. Both names lead to the one Settings object, and the program changed that object. Only assigning a new object to config.settings would leave the name from the from-import behind.

@singleton above class Logger replaces Logger with a function that makes one Logger and keeps it. What does class FileLogger(Logger): pass do?

  • It makes a class FileLogger that shares Logger's one object
  • It stops with TypeError: function() argument 'code' must be code, not str
  • It makes an ordinary subclass of Logger
  • It stops with NameError: name 'Logger' is not defined

Answer: It stops with TypeError: function() argument 'code' must be code, not str. The name Logger now refers to a function, and a function can't be a parent class.

get_logger(name) is decorated with @functools.cache, prints "making" and the name, and returns a new list. The program calls get_logger("shop"), get_logger("admin") and get_logger("shop") again. How many lines does it print?

  • One
  • Three
  • None
  • Two

Answer: Two. The cache keeps one result for each argument, so the second call with "shop" returns the list made the first time without running the function.

PAYMENTS = {"card": Card(), "paypal": PayPal()}, and Card's __init__ sets self.total = 0. After a = PAYMENTS["card"], b = PAYMENTS["card"] and a.total += 5, what does print(b.total) print?

  • 5
  • 0
  • It stops with KeyError
  • It stops with TypeError: 'Card' object is not callable

Answer: 5. The brackets made one Card when the dictionary was made, and every lookup returns that same object.

make_sender(channel) returns EmailSender() if channel == "email", TextSender() elif channel == "text", and has nothing after that. What does make_sender("sms").send("Ada") do?

  • It sends a text, the closest match
  • It stops with KeyError: 'sms'
  • It stops with ValueError
  • It stops with AttributeError: 'NoneType' object has no attribute 'send'

Answer: It stops with AttributeError: 'NoneType' object has no attribute 'send'. No branch matches, so the function ends without a return line and returns None, and None has no send().

Money's from_pounds is a @staticmethod that returns Money(round(pounds * 100)), and Tip is a subclass of Money with nothing else in it. What does print(type(Tip.from_pounds(1.5)).__name__) print?

  • Tip
  • It stops with TypeError
  • Money
  • float

Answer: Money. The method names Money, so it makes a Money whichever class it's called on. A @classmethod that calls cls(...) would make a Tip.

student(total) returns total * 0.9, and checkout(total, discount) returns discount(total). What does checkout(80, student()) do?

  • It stops with TypeError: student() missing 1 required positional argument: 'total'
  • It returns 72.0
  • It returns 80
  • It stops with TypeError: 'float' object is not callable

Answer: It stops with TypeError: student() missing 1 required positional argument: 'total'. student() calls the function right there, with no total, before checkout even starts. Pass the function itself: checkout(80, student).

Continue this course

Frequently asked questions

Is a module-level object safe with threads?

Making it is. Python locks a module while it runs it for the first time, so even when several threads import it at once, it runs once and every thread gets the same object: measured with four threads on CPython 3.10 to 3.14. Changing that object from several threads at the same time needs a lock, which Threading & the GIL covers. A __new__ singleton has no such protection: with a short pause added between its check and its assignment, four threads made four different objects.

What is the Borg pattern?

Many objects that share one __dict__, so they share every attribute without being one object. The Borg class's __init__ sets self.__dict__ to a dictionary kept on the class. The catch is that every subclass shares that same dictionary: after Settings().debug = False, Cache().debug is False too, though Cache is a different class built on Borg.

Why does mypy say "object" has no attribute "pay" for my dictionary of classes?

mypy 1.19.1 reads {"card": Card, "paypal": PayPal} as a dictionary of things that make an object, so for PAYMENTS["card"]().pay(3) it reports error: "object" has no attribute "pay". Describe what every class offers with a Protocol and annotate the dictionary as PAYMENTS: dict[str, Callable[[], Payment]], and mypy accepts it. Advanced Type Hints (Generics, Protocol, TypedDict) covers Protocol.

Are Enum members singletons?

Each member is one object, however you reach it: Size(1) is Size.SMALL and Size["LARGE"] is Size.LARGE are both True. Enums (the enum module) covers them.

Is Python's @decorator the Decorator pattern?

Not quite. Both wrap something to add behaviour, but Python's @ wraps a function or a class once, when it's defined, as in Decorators & Advanced Features. The pattern of that name wraps one object in another that has the same methods, adds something, and passes each call on, while the program runs.

What about the Observer pattern?

Closures & Lexical Scope in Real Projects built one: its event bus lets code register a handler for an event name with on(), and emit() calls every handler registered for that event.

Related lessons