Skip to content

Design Patterns in Python

Beginning of the lesson

Design Patterns in Python

Classic patterns, rewritten the Pythonic way with modules, first-class functions and protocols

Big Idea: A design pattern is a named, reusable solution to a recurring design problem. The famous "Gang of Four" catalogue was written for static languages like C++ and Java. Python is more dynamic: functions are objects, modules are cached singletons, and duck typing means you rarely need an interface hierarchy. So in Python most patterns become lighter - and a few almost disappear.
By the end you will be able to:
  • explain why a Python module is already a Singleton;
  • replace a Factory class hierarchy with a registry dict of callables;
  • implement the Strategy pattern by passing a plain function;
  • build an Observer with a list of subscriber callables;
  • use typing.Protocol for structural typing instead of ABCs.

1. What a pattern is - and Python's twist

A pattern is not a library or a language feature; it is a shape of a solution that keeps re-appearing. Naming those shapes gives a team shared vocabulary: saying "let's use a Strategy here" communicates a whole design in two words.

The catch is that many textbook patterns exist to work around limitations of static, class-only languages. In those languages you cannot pass a function around, so you wrap the function in an object with a single method. Python can pass functions, store them in dicts, and swap behaviour at runtime, so the object wrapper is often unnecessary ceremony. The professional habit is: reach for the simplest tool that expresses the intent, and only add classes when they earn their keep.

PatternClassic OOP formPythonic form
Singletonclass that hides its constructora module (already single per process)
Factorycreator class hierarchya dict registry of callables
Strategystrategy interface + concrete classespass a first-class function
Observersubject + observer interfacesa list of subscriber callbacks

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers