Undo, Redo and Queues: The Command Pattern in Python

This article explains how the Command pattern turns requests into objects that Python programs can store, queue, undo and redo, and why reliable undo must restore recorded rather than assumed state.

Close view of the head of a green tree python, with a vertical pupil and yellow lip scales, resting on its own coils
Photo by David Clode on Unsplash

A button, a keyboard shortcut or a menu item that calls the code it triggers directly cannot record what it did, delay it, repeat it or reverse it, because the action exists only as a function call that is gone once it returns. The present article examines the Command pattern, which turns each request into an object that holds everything needed to execute it later and, optionally, to undo it. It builds an editor with undo and redo based on recorded state, groups commands into macros, shows the lighter Python forms of the pattern, commands as data classes and as partial functions, and analyses the errors that make an undo history unreliable. Treating an action as a value that can be stored and reversed, instead of as a call that disappears, is the secret weapon of the Command pattern.

Orders as Objects

Strategy games let a player queue several orders for a unit, so that it moves, then attacks, then returns, and the pending orders remain visible and can be cancelled before they run. The Command pattern gives programs the same property: each request is an object with a method execute, created by one part of the program and run by another, the invoker, which can keep it in a history. The analogy, however, stops at this point, because an order already carried out in a game cannot be taken back, whereas a command that records the state it changed can restore it with undo.

class Document:
    def __init__(self):
        self.text = ""

class Append:
    def __init__(self, document, fragment):
        self.document = document
        self.fragment = fragment
        self.previous = None

    def execute(self):
        self.previous = self.document.text
        self.document.text += self.fragment

    def undo(self):
        self.document.text = self.previous

class Editor:
    def __init__(self):
        self.undo_stack = []
        self.redo_stack = []

    def run(self, command):
        command.execute()
        self.undo_stack.append(command)
        self.redo_stack.clear()

    def undo(self):
        command = self.undo_stack.pop()
        command.undo()
        self.redo_stack.append(command)

    def redo(self):
        command = self.redo_stack.pop()
        command.execute()
        self.undo_stack.append(command)

doc, editor = Document(), Editor()
editor.run(Append(doc, "Hello"))
editor.run(Append(doc, ", world"))
editor.undo()
print(repr(doc.text))  # Output: 'Hello'
editor.redo()
print(repr(doc.text))  # Output: 'Hello, world'

Each command records the text that existed before it ran, so undo restores exactly that state, whatever it was. The editor knows nothing about documents: it only executes, stores and reverses commands. Running a new command clears the redo stack, since the commands undone earlier were based on a history that no longer exists.

Macros and Bounded Histories

A macro is a command that contains other commands; it executes them in order and undoes them in the reverse order, so that each one is reversed while the state it recorded is still the current one. A history that grows without limit retains every command ever run, so editors usually keep only the most recent ones, which a deque with a maximum length does automatically, as described in the article devoted to deque.

from collections import deque

class Document:
    def __init__(self):
        self.text = ""

class Append:
    def __init__(self, document, fragment):
        self.document, self.fragment, self.previous = document, fragment, None

    def execute(self):
        self.previous = self.document.text
        self.document.text += self.fragment

    def undo(self):
        self.document.text = self.previous

class Macro:
    def __init__(self, *commands):
        self.commands = commands

    def execute(self):
        for command in self.commands:
            command.execute()

    def undo(self):
        for command in reversed(self.commands):
            command.undo()

doc = Document()
history = deque(maxlen=2)
signature = Macro(Append(doc, "\n--\n"), Append(doc, "Regards"))
for command in (Append(doc, "Dear team,"), Append(doc, " thanks."), signature):
    command.execute()
    history.append(command)

print(len(history))      # Output: 2
history.pop().undo()
print(repr(doc.text))    # Output: 'Dear team, thanks.'

The macro is undone as a single step, and the history keeps only the last two commands, so the first one can no longer be undone. Undoing a macro in reverse order matters because each inner command restores the text that existed just before it ran.

Lighter Commands in Python

When commands do not need to be undone, a function that has captured its arguments is already a command: functools.partial builds one from any function, the same technique used for parameterized behaviour in the article devoted to the Strategy pattern. When commands must be stored, logged or sent to another process, a data class describes them as plain records, and a separate function executes them, as in the article devoted to data classes.

from dataclasses import dataclass, asdict
from functools import partial

queue = [partial(print, "backup started"), partial(print, "backup", "finished", sep=" ")]
for command in queue:
    command()
# Output: backup started
# Output: backup finished

@dataclass(frozen=True)
class Transfer:
    source: str
    target: str
    amount: int

def execute(command, balances):
    balances[command.source] -= command.amount
    balances[command.target] += command.amount

balances = {"a": 100, "b": 0}
log = [Transfer("a", "b", 30), Transfer("a", "b", 20)]
for command in log:
    execute(command, balances)
print(balances)          # Output: {'a': 50, 'b': 50}
print(asdict(log[0]))    # Output: {'source': 'a', 'target': 'b', 'amount': 30}

The partial functions form a queue of deferred actions with no class at all. The transfers are frozen records that can be serialized with asdict, written to a log and replayed later to rebuild the balances, which is the principle of transaction logs; the behaviour lives in execute, outside the data.

Pitfalls of the Command Pattern

An undo history is only as reliable as the least careful command in it, so the errors of the pattern usually appear long after the command that caused them. Six pitfalls are distinguished, which are the following:

  1. Undo by opposite action. Reversing "turn on" with "turn off" is wrong when the light was already on; undo must restore the recorded previous state.
  2. Redo after a new command. Keeping the redo stack after a new command lets the user redo actions based on a state that no longer exists.
  3. Failed commands in the history. A command that raises halfway must not be stored, or undo will try to reverse an action that never completed.
  4. Shared mutable arguments. A command that keeps a reference to a list or dictionary may undo to a value that was modified afterwards; copying the recorded state avoids it.
  5. Unbounded history. Every stored command retains the state it recorded, so memory grows with the session unless the history has a limit.
  6. Commands for everything. A direct call is clearer when the action never needs to be stored, queued or undone.

The first pitfall is reproduced in the following example.

class Light:
    def __init__(self, on):
        self.on = on

class NaiveTurnOn:
    def __init__(self, light):
        self.light = light

    def execute(self):
        self.light.on = True

    def undo(self):
        self.light.on = False

class TurnOn:
    def __init__(self, light):
        self.light, self.previous = light, None

    def execute(self):
        self.previous = self.light.on
        self.light.on = True

    def undo(self):
        self.light.on = self.previous

naive_light, careful_light = Light(on=True), Light(on=True)
naive, careful = NaiveTurnOn(naive_light), TurnOn(careful_light)
naive.execute(); naive.undo()
careful.execute(); careful.undo()
print(naive_light.on, careful_light.on)  # Output: False True

Both lights were on before the command, and only the command that recorded the previous state returns the light to it; the naive version turns off a light that it never turned on.

Choosing a Form of Command

Consequently, the form depends on whether the action must be undone, stored or merely deferred, as the following table summarizes.

Situation Recommended approach
Deferred actions without undo Functions or functools.partial
Actions to log, serialize or replay Data class records and an executing function
Actions that must be undone and redone Command objects that record the previous state
Several actions undone as one A macro command, undone in reverse order
A long session with an undo history A bounded history with deque(maxlen=...)
An action that is never stored A direct call

Conclusion

It is concluded that the Command pattern turns a request into an object that can be executed later, stored in a history and, when it records the state it changed, undone and redone, and that Python also offers lighter forms through partial functions and data class records. This magic depends on undo restoring recorded state rather than assumed state, on clearing the redo stack after a new command and on bounding the history. Capturing the whole state of an object in a snapshot that can be restored later, instead of recording the effect of each command, is the purpose of the Memento pattern, which is developed in a future article of this series.