Sub topic 9
Storing snapshots instead of commands
This chapter assumes you have read the earlier chapters. You should know the two-stack model, the do, undo and redo operations, and why a new action clears the redo stack. It also assumes you can read Python classes and know the difference between copying a value and sharing a reference.
The idea
So far each history entry has been a command. A command knows how to apply and revert itself. A snapshot is a saved copy of the whole state at one moment. With snapshots, the history stores states instead of actions. Undo means "go back to the previous state". Nothing needs to know how to reverse anything.
The two stacks work the same way. The only difference is what goes on them.
A snapshot history
The class below keeps the current state in a field. The undo and redo stacks hold older states. The edit method makes a deep copy, lets you change the copy, and records the result. This protects the saved states from later changes.
import copy
class SnapshotHistory:
def __init__(self, state):
self.state = state
self._undo = []
self._redo = []
def do(self, new_state):
self._undo.append(self.state)
self.state = new_state
self._redo.clear()
def edit(self, change):
new_state = copy.deepcopy(self.state)
change(new_state)
self.do(new_state)
def undo(self):
if not self._undo:
return False
self._redo.append(self.state)
self.state = self._undo.pop()
return True
def redo(self):
if not self._redo:
return False
self._undo.append(self.state)
self.state = self._redo.pop()
return True
history = SnapshotHistory("")
history.do("Hello")
history.do("Hello world")
print(history.state) # Hello world
history.undo()
print(history.state) # Hello
history.redo()
print(history.state) # Hello world
history.undo()
history.do("Hello!")
print(history.state) # Hello!
print(history.redo()) # False
notes = SnapshotHistory([])
notes.edit(lambda s: s.append("a"))
notes.edit(lambda s: s.append("b"))
print(notes.state) # ['a', 'b']
notes.undo()
print(notes.state) # ['a']The text example behaves exactly like the command version from the worked editor. The empty-stack checks and the redo clearing are unchanged.
The aliasing bug
The most common snapshot error is saving a reference instead of a copy. Suppose do pushed a list and you then called append on that same list. Every entry on the undo stack would point at the one list you just changed. Undo would appear to do nothing, because all the snapshots would already show the newest state.
Strings and tuples are immutable, so they are safe to store directly. Lists, dicts and objects need a copy. edit handles this by always changing a fresh deep copy.
Snapshots versus commands
| Concern | Commands | Snapshots |
|---|---|---|
| Memory per entry | Small, only the data needed to reverse | Whole state, or a large share of it |
| Code per action | Each action needs `apply` and `revert` | None, only a copy of the state |
| Risk of bugs | A wrong `revert` leaves the state corrupt | Shared references in the saved copies |
| Irreversible actions | Hard, such as deleting without saving the old data | Easy, the old state is already stored |
| Fits best | Large state, small edits | Small state, or state that is hard to reverse |
A one-character edit in a 10 MB document costs a few bytes as a command. It costs another 10 MB as a naive snapshot. For a small settings form, a snapshot is simpler and the memory cost does not matter.
Reducing the cost
Two common techniques make snapshots cheaper:
- Use immutable data structures. If an edit builds a new state that shares unchanged parts with the old one, each snapshot stores only what changed.
- Cap the history, as in the bounded history chapter. Replacing the undo list with
deque(maxlen=limit)works here too.
You can also mix both approaches. Some editors store commands for frequent small edits and take a full snapshot every few hundred steps.
Exercise
A snapshot history stores a list of dictionaries. A teammate changes do so it appends self.state to the undo stack and then edits self.state in place with self.state.append(item). What goes wrong, and how do you fix it?
Show answer
The undo stack now holds a reference to the same list that is being modified, so every saved snapshot shows the latest edit and undo restores nothing useful. Fix it by copying before changing, for example by using edit, which deep-copies the state, applies the change to the copy and then calls do with it.