Sub topic 7
Undo and redo when there is nothing to do
This chapter assumes you know Python classes, the push and pop operations of a stack, and the two-stack History class from the previous chapters. It covers what undo() and redo() should do when their stack is empty.
Why empty stacks happen
Both stacks start empty, so a user can press undo before doing anything. Two other situations produce the same state:
- The user undoes every action. The undo stack is now empty.
- The user redoes every undone action, or performs a new action. The redo stack is now empty.
Pressing Ctrl+Z or Ctrl+Y in these states is normal. The history manager has to handle it without crashing and without changing the document.
The unguarded version fails
Suppose undo() skips the check:
def undo(self):
command = self._undo.pop() # IndexError if the stack is empty
command.revert()
self._redo.append(command)list.pop() on an empty list raises IndexError: pop from empty list. An ordinary key press would then crash the program or need a try/except at every call site.
The guard
The History class from this tutorial checks first and returns early:
def undo(self):
if not self._undo:
return False
command = self._undo.pop()
command.revert()
self._redo.append(command)
return TrueAn empty list is falsy, so not self._undo is true exactly when there is nothing to undo. The method returns before it touches any stack or command. redo() has the same shape with self._redo.
Why return a boolean
The return value tells the caller whether anything happened. That has two uses:
- A user interface can grey out the Undo menu item, or show "Nothing to undo", based on the result.
- A test can check both the document and the return value.
Returning False is not the only valid design. Compare the options:
| Approach | Caller must | Good when |
|---|---|---|
| Return `False` | Optionally check the result | Empty stacks are routine, as in an editor |
| Raise a custom exception | Catch it | Calling undo with no history is a bug in your program |
| Do nothing, return `None` | Nothing | You never need to report the outcome |
For an editor, returning a boolean fits best. Pressing undo too many times is something users do all the time.
Seeing it run
This example is complete. It uses a minimal command so it does not depend on the text editor:
class History:
def __init__(self):
self._undo = []
self._redo = []
def do(self, command):
command.apply()
self._undo.append(command)
self._redo.clear()
def undo(self):
if not self._undo:
return False
command = self._undo.pop()
command.revert()
self._redo.append(command)
return True
def redo(self):
if not self._redo:
return False
command = self._redo.pop()
command.apply()
self._undo.append(command)
return True
class Add:
def __init__(self, items, value):
self.items = items
self.value = value
def apply(self):
self.items.append(self.value)
def revert(self):
self.items.pop()
items = []
history = History()
print(history.undo()) # False: nothing done yet
print(history.redo()) # False: nothing undone yet
history.do(Add(items, "a"))
print(history.undo()) # True
print(history.undo()) # False: undo stack is empty again
print(items) # []
print(history.redo()) # True
print(history.redo()) # False: redo stack is empty again
print(items) # ['a']Each False leaves items unchanged. The True calls are the only ones that move a command between stacks.
Common mistakes
- Popping before checking. The check must come first. If you pop and then test the result, the command is already gone from the stack.
- Changing state before returning. An early return must not call
revert()orapply(). - Forgetting the redo side.
redo()needs its own guard, because the redo stack is empty in most situations, including right after any new action. - Assuming a bounded history never empties.
BoundedHistoryuses adequewithmaxlen. Old commands drop off, but the deque can still be empty, so the guard stays in place.
Exercise
Exercise
A fresh History object receives these calls in order: do(cmd), undo(), undo(), redo(), redo(), redo(). What does each of the last four calls return, and why?
Show answer
The second undo() returns False, because the first undo moved the only command to the redo stack and the undo stack is empty. The first redo() returns True, because it moves cmd back to the undo stack. The second and third redo() calls return False, because the redo stack is empty and the guard returns before changing anything. In order: False, True, False, False.