Design patterns, the Python way
Last updated
Some problems come up in program after program, and programmers have named the usual ways to solve them. These are design patterns. In this lesson you'll meet five that the library system uses: a strategy for fines, a factory that makes the right kind of item, a repository that hides where data is saved, an iterator written as a generator, and the one-of-a-kind object. Python's functions and modules make several of them much smaller than in other languages.
By the end of this lesson you can
- Swap behaviour in and out with the strategy pattern, using a class or a plain function
- Make the right kind of object from saved data with a factory class method
- Hide where data is saved behind a repository, and write an iterator as a generator with
yield - Explain why a module usually does the job of a singleton in Python
Strategy, with a class
Members pay fines in different ways: 25 cents a day up to 500 for most, nothing for staff. The strategy pattern puts each way in an object of its own, and lets a member hold whichever one applies. It's the composition from lesson 4.15, used for behaviour.
- +name: str
- +fine_rule: NoFines | StandardFines
- +__init__(name: str, fine_rule: NoFines | StandardFines)
- +fine_for(days_late: int): int
- +fine_for(days_late: int): int
- +fine_for(days_late: int): int
- Class StandardFines; no attributes of its own; methods: fine_for.
- Class NoFines; no attributes of its own; methods: fine_for.
- Class Member; attributes: name, fine_rule; methods: __init__, fine_for.
- Member holds one NoFines in fine_rule.
Member.fine_for passes the work to its rule on line 17. A new rule, say half fines for students, is one more class, and Member doesn't change.
But look at what each rule class is: a class with one method and nothing else. That's a lot of code for one function. In some languages a class is the only way to pass behaviour around. Python has a smaller way.
Strategy, with a function
Lesson 2.5 showed that functions are values: you can store one in a name or an attribute, and call it later. So the rule can just be a function.
Same output for Sam and Lee, with less code. self.fine_rule(days_late) on line 15 calls whatever function the member was given. Kim's one-off rule on line 20 is a lambda, with no named class or function at all.
Neither version is an error. It's a judgement call:
| Class | Function | |
|---|---|---|
| Lines of code | A class per rule, each with one method | A function per rule |
| A one-off rule | Needs another class | A lambda will do |
| Rules that need their own settings, like a rate and a cap | Natural: attributes on the object | Possible, but a class is clearer |
| Rules with several methods | Natural | Awkward |
Start with a function. Switch to a class when the rule needs its own settings or more than one method.
Factory with @classmethod
Data saved in a file comes back as dicts. Each dict says what kind of item it was, and the program must make a Book from one and a DVD from another. A factory is a method whose job is to pick the right class and make the object.
from_dict is a class method, like Book.from_csv_row in lesson 3.4. Line 8 maps each kind's name to its class. Classes are values too, so they can sit in a dict. Line 9 picks one, and line 10 calls it to make the object. The loop never mentions Book or DVD.
Code that loads items now has one place to ask. Adding magazines means one more class and one more entry in the dict.
Repository: one way to save
A repository is an object that saves and loads data, with the same methods whatever it saves to. The rest of the program calls save and load and never knows whether the data went to a file, a database or nowhere at all.
- #_saved: list[str]
- +__init__()
- +save(titles: list[str])
- +load(): list[str]
- +path: str
- +__init__(path: str)
- +save(titles: list[str])
- +load(): list[str]
- Class MemoryRepository; attributes: _saved; methods: __init__, save, load.
- Class JsonRepository; attributes: path; methods: __init__, save, load.
add_title on line 28 works with either repository, through duck typing (lesson 4.10): both have save and load. MemoryRepository keeps data in a list, which is handy in tests because it writes no files. JsonRepository writes the file you can open under the output. Lesson 4.14 shows how to write down what every repository must have.
Iterator, with a generator
An iterator hands out items one at a time, which is what a for loop asks for. In Python the easy way to write one is a generator: a function that uses yield instead of return.
Each yield on line 10 gives the loop one loan, then the function pauses where it is. When the loop asks for the next item, it carries on from just after the yield. When the function ends, the loop ends.
next(late)on line 17 asks for just the first item.list(...)on line 18 collects them all.
Watch it run and follow how the program moves between the loop on line 14 and overdue. A generator never builds the whole list, so it's cheap even for a long list of loans.
Why a module is usually the singleton
A singleton is a class that only ever has one object, like the library's settings. In Java this takes a careful class. In Python, a module is already one of a kind. The first import runs the file. Every later import of the same module gives back the very same module object.
"Loading settings" prints once, though the module is imported twice. Line 4 shows both names are labels on one module (lesson 3.1), so changing a setting through one name is seen through the other.
So when you need one shared thing, put it in a module. You rarely need a singleton class in Python.
In other languages
This step is optional. It's for anyone who will meet Java or Rust later.
| Python | Java | Rust | |
|---|---|---|---|
| Strategy | A function, or an object with a method | An interface and a class per strategy (or a lambda since Java 8) | A closure, or a trait object |
| Factory | @classmethod | A static method | A function in the impl block |
| Iterator | A generator with yield | A class with hasNext() and next() | A type with the Iterator trait |
| Singleton | A module | A class with a private constructor and one static instance | A static value |
Many patterns were first written down for languages where everything has to be a class. In Python some shrink to a function or a module. The idea behind each one still matters.
Check what you learned
Three questions. Pick or type an answer, then check it.
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- The Python Tutorial: Generators
- The Python Language Reference: The yield statement
- Built-in Functions: next
- The Python Tutorial: More on Modules: a module runs once, the first time it is imported
- Programming FAQ: How do I share global variables across modules?: a module as the single place for settings
- Built-in Functions: classmethod
- OMG Unified Modeling Language (UML) 2.5.1: the standard the class diagrams follow
- Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides: Design Patterns (1994): the book that named Strategy, Factory Method, Iterator and Singleton
- Martin Fowler: Repository: the repository pattern
- Java API: Iterator: iterators in Java
- The Rust Programming Language: Processing a Series of Items with Iterators: iterators in Rust