Sub topic 10
Capping how much history is kept
This chapter assumes you know Python classes, the stack operations push and pop, and the History class from the earlier chapters. It adds one feature to that class: a limit on how many actions the undo stack keeps.
Why history needs a limit
Every call to do() adds a command to the undo stack. A user who edits for hours can create tens of thousands of commands. Each command holds references to a document, a position, and a string. A command that removes a large block of text may hold that whole block so it can restore it.
Without a limit, memory grows for as long as the program runs. Most programs only need the last several dozen actions. Undoing something from two hours ago is rare.
Dropping the oldest action
The undo stack is last-in, first-out. The newest command sits at the top, and the oldest sits at the bottom. When the stack is full, the command to discard is the oldest one, which is at the bottom.
A Python list is a poor fit for this. list.pop(0) removes the bottom item, but it shifts every other item and takes O(n) time. A collections.deque with a maxlen solves this. When you append to a full deque, the item at the opposite end is dropped automatically, and the cost is O(1).
The implementation
BoundedHistory subclasses History and replaces the undo list with a bounded deque. Nothing else changes. undo() calls pop(), which works the same on a deque. redo() calls append(), which also works the same.
from collections import deque
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 BoundedHistory(History):
def __init__(self, limit):
if limit < 1:
raise ValueError("limit must be at least 1")
super().__init__()
self._undo = deque(maxlen=limit)
class Counter:
def __init__(self):
self.value = 0
class Add:
def __init__(self, counter, amount):
self.counter = counter
self.amount = amount
def apply(self):
self.counter.value += self.amount
def revert(self):
self.counter.value -= self.amount
counter = Counter()
history = BoundedHistory(3)
for n in range(1, 6):
history.do(Add(counter, n))
print(counter.value) # 15
undone = 0
while history.undo():
undone += 1
print(undone) # 3
print(counter.value) # 3Five actions were applied, but only three could be undone. The actions that added 1 and 2 were dropped from the history, so their effect stays in counter.value.
Behavior to know about
- Dropped commands are not reverted. Dropping a command only removes the ability to undo it. The change it made stays in the document.
- The redo stack stays bounded too. Commands reach the redo stack only by moving from the undo stack, so it can never hold more than
limitcommands. - Undo and redo never trigger a drop.
undo()removes one command beforeredo()adds one back, so the deque is never over its limit at that point. Onlydo()can push out an old command. - A limit of 0 is a bug waiting to happen.
deque(maxlen=0)discards every command at once.do()would still apply the action, but the user could never undo it. The constructor above rejects that value.
Choosing a limit
The right number depends on how large each command is. Commands that store small values, such as an insert of a few characters, are cheap, and a limit of 1,000 is reasonable. Commands that store large payloads, such as deleted images, are expensive, so use a smaller limit. Some programs limit by total bytes instead of by count. That takes more bookkeeping, because you must track each command's size as it enters and leaves the stack.
Exercise
A BoundedHistory has a limit of 2. You call do() with commands A, B and C, then call undo() three times. What does each undo() return, and is A's effect still in the document?
Show answer
The first two calls return True and undo C and B. The third returns False, because A was dropped when C was added and the stack was full. A's effect is still in the document, since dropping a command does not revert it.
Exercise
Why is deque(maxlen=limit) better than calling self._undo.pop(0) on a list when the stack is full?
Show answer
pop(0) on a list shifts every remaining item, so it costs O(n). A deque with maxlen drops the oldest item automatically in O(1) when you append.