Command Pattern in Python

Esteban Thilliez
Tech Tavern
Published in
5 min readFeb 16, 2023

--

Command Pattern in Python
Photo by Markus Spiske on Unsplash

This story is part of the “Design Patterns” series. You can find the other stories of this series here:

You can also find all the code used through this series on GitHub.

The Command pattern is a design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time.

This allows for decoupling of objects that invoke operations from the objects that perform those operations.

Problems the Command Pattern can Solve

Imagine we’re building a program that simulates a vending machine. The program might have a single function called dispensethat is responsible for dispensing a product from the vending machine. This function would take in the product code, check the inventory, and dispense the product if it is available.

class VendingMachine:
def __init__(self):
self.inventory = {"cola": 5, "water": 10, "juice": 8}

def dispense(self, product_code):
if product_code not in self.inventory…

--

--

Esteban Thilliez
Tech Tavern

I’m Esteban, and I enjoy writing about programming, trading, productivity, knowledge management, books, etc! esteban-thilliez.com / contact@esteban-thilliez.com