Object-oriented programming · lesson 16 of 17
Parts in this lesson
Aself.fine_rule(days)strategy: a swappable part
BLibraryItem.from_dict(data)factory: the right class
Crepository.save(…)repository: saving, hidden
Dyield loaniterator: one at a time
Eimport settingsa module: one of a kind

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.

Strategy: a member holds a fine rule, and each rule is its own class
100%
Member
  • +name: str
  • +fine_rule: NoFines | StandardFines
  • +__init__(name: str, fine_rule: NoFines | StandardFines)
  • +fine_for(days_late: int): int
StandardFines
  • +fine_for(days_late: int): int
NoFines
  • +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.
Step 1 code main.py
Edit the code, then run it again

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.

Step 2 code main.py
Edit the code, then run it again

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:

Strategy as a class or a function
ClassFunction
Lines of codeA class per rule, each with one methodA function per rule
A one-off ruleNeeds another classA lambda will do
Rules that need their own settings, like a rate and a capNatural: attributes on the objectPossible, but a class is clearer
Rules with several methodsNaturalAwkward

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.

Step 3 code main.py
Edit the code, then run it again

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.

Repository: two classes with the same methods, saving in different places
100%
MemoryRepository
  • #_saved: list[str]
  • +__init__()
  • +save(titles: list[str])
  • +load(): list[str]
JsonRepository
  • +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.
Step 4 code main.py
Edit the code, then run it again

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.

Step 5 code main.py
Edit the code, then run it again

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.

Step 6 code
Edit the code, then run it again

"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.

Patterns in three languages
PythonJavaRust
StrategyA function, or an object with a methodAn interface and a class per strategy (or a lambda since Java 8)A closure, or a trait object
Factory@classmethodA static methodA function in the impl block
IteratorA generator with yieldA class with hasNext() and next()A type with the Iterator trait
SingletonA moduleA class with a private constructor and one static instanceA 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.

What does this program print?
def countdown(n):
    while n > 0:
        yield n
        n -= 1


print(list(countdown(3)))
A fine rule is one short calculation. What's the simplest way to make it swappable?
Why is a module enough for one shared set of settings?

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.

All sources for Simple Python