Python Design Patterns

Command Pattern in Python

Command separates the object requesting work from the receiver that performs it.

What is Command Pattern?

Command separates the object requesting work from the receiver that performs it.

Represent a request as an object that can be queued, logged, or undone.

When should you use it?

  • Solve recurring object-design problems with proven structures.
  • Decouple responsibilities so code is easier to extend and test.
  • Use shared design vocabulary when discussing architecture with a team.

Example code

Run code →
main.py
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())

Expected output

Light on
Light off

How it works

Switch invokes command objects, and each command knows which Light operation to call.

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.

  1. Replace the sample domain while preserving the pattern structure.
  2. Compare the pattern with a simpler implementation and explain the tradeoff.
  3. Write tests for each participant before adding another implementation.
Run in Python IDE →