Command Pattern in Python
Turn a request into an object you can queue, log or undo, like a light switch with an undo button.
- Commands with execute() and undo()
- Invoker, command and receiver
- Building an undo history
- 1
remoteInvoker - 2
LightCommandCommand - 3
light.on()Receiver: Light on
A request you can store
The problem
Undo buttons, task queues, macros and remote controls all need to treat an action as something you can store, pass around and run later. A plain method call happens immediately and is gone.
Think of it like this
The Command pattern is like an order slip in a restaurant. The waiter writes "table 4, soup" on a slip and hangs it in the kitchen. The cook runs the order later, and the slips can be kept, reordered or cancelled.
LightCommand(light, "on")🧾 Write the request on a slipself.light, self.action📌 The slip knows who and whatcommand.execute()👨🍳 Run the request when it is time[...] list of commands📚 Slips can be stored, queued or undoneThe Command pattern wraps a request, its receiver and its action in an object with an execute method, so it can be stored, queued, logged or undone.
Key points
LightCommandstores the receiver (light) and the name of the action ("on"or"off").execute()usesgetattr(self.light, self.action)()to look up and call that method.- The loop runs two stored commands without knowing what they do.
- The commands could be kept in a list to replay or undo them.
When should you use it?
- Undo and redo histories.
- Queues of tasks to run later or on another worker.
- Buttons, menus and keyboard shortcuts that trigger configurable actions.
When not to use it
- A direct call that runs once: wrapping it in a class adds noise.
- In Python, a stored function or
functools.partialis often enough.
Example code
class Light:
# Command: package a request as an object for later execution.
def on(self): return "Light on"
def off(self): return "Light off"
class LightCommand:
def __init__(self, light, action):
self.light, self.action = light, action
def execute(self):
# Store a request as data that can be invoked later.
return getattr(self.light, self.action)()
light = Light()
for command in [LightCommand(light, "on"), LightCommand(light, "off")]:
print(command.execute())
Result of running the code
Light on
Light off
Code explanation
Each LightCommand remembers which light to control and which action to run, but does nothing when created. execute() looks up the method named by self.action on the light with getattr and calls it. The loop then runs the stored commands one after another, printing Light on and Light off.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Replace the sample domain while preserving the pattern structure.
- Compare the pattern with a simpler implementation and explain the tradeoff.
- Write tests for each participant before adding another implementation.
Common mistakes
Running the action when creating the command
The point is to delay the call until execute().
command = LightCommand(light, light.on())
command = LightCommand(light, "on")
Finished this lesson?
Mark it as learned to track your progress.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
All challenges