Some of the most common design patterns implemented in Python.
⚠️ READ THIS⚠️ Design patterns are spoonfeed material for brainless programmers incapable of independent thought, who will be resolved to producing code as mediocre as the design patterns they use to create it.
— Christer Ericson, VP of Technology at Activision Central Tech.
When I started programming, I thought that a serious programmer should have to know all major design patterns described in the book Design Patterns: Elements of Reusable Object-Oriented Software, and religiously write code that would follow them.
Over time, I realized that only a few of these patterns are actually good, most of them are bad, some others are completely unnecessary, especially in a dynamic language like Python. In fact, I don't recall having to use most of them, except for maybe Decorator, Observer and Strategy.
Before reading the code in this repository, I suggest you have a look at these resources to understand whether a particular design pattern suits your use-case or not:
- Design Patterns and Anti-Patterns, Love and Hate — Yegor Bugayenko
- Design Patterns in Dynamic Languages — Peter Norvig
This project uses pyenv and pyenv-virtualenv to manage the Python virtual environment, and poetry to manage the project dependencies.
If you don't have python 3.x.x
, you have to install it. For example, I'm using 3.7.9
.
pyenv install 3.7.9
Create a virtual environment and activate it.
pyenv virtualenv 3.7.9 design_patterns
pyenv activate design_patterns
Install all the dependencies from the poetry.lock
file.
poetry install
Every python file contains an implementation of a design pattern and a simple example that can help you understand where the pattern might be useful.
For example
python observer.py
python strategy.py
# etc...
If you want you can run all tests with:
poetry run pytest --verbose
You can also test the MVC pattern with:
cd mvc
poetry run python model_view_controller.py
# or simply
python mvc/model_view_controller.py
If you use pyenv and get the error "No module named '_ctypes'"
on Ubuntu, you are probably missing the libffi-dev
package. See this answer.
If you get Error: pg_config executable not found.
on Ubuntu, install the libpq-dev
package. See here.