Undo with a history stack

Step 2: Undo with a history stack

A single snapshot is useful, but a real editor keeps a whole history. The caretaker (the part that manages saved snapshots) lives right inside the Editor as a list used like a stack.

The list _history is already created for you in init. Implement two methods:

  • backup() takes a snapshot of the current content with save() and pushes it onto _history.
  • undo() pops the most recent snapshot off _history and restores it. If _history is empty, undo does nothing.

Because a stack is last in, first out, calling undo repeatedly walks backward through your edits in reverse order. The typical flow is: call backup before you make a change, then undo to step back to the snapshot you took.

Hints
Starter code
class Memento:
    def __init__(self, state):
        self._state = state

    def get_state(self):
        return self._state


class Editor:
    def __init__(self):
        self.content = ""
        self._history = []

    def save(self):
        return Memento(self.content)

    def restore(self, memento):
        self.content = memento.get_state()

    def backup(self):
        """Push a snapshot of the current content onto the undo stack."""
        # TODO: append self.save() to self._history
        pass

    def undo(self):
        """Pop the most recent snapshot and restore it (no-op if empty)."""
        # TODO: if history is non-empty, pop the last memento and restore it
        pass
Write it on a laptop

The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.