Snapshot and restore

Step 1: Snapshot and restore

The Memento pattern lets you capture an object's internal state in a separate snapshot object and restore it later, without exposing how that state is stored.

Here the originator is an Editor that holds some content (a string). A Memento wraps a copy of that content in a private field so nobody outside can read it directly.

Implement two methods on Editor:

  • save() creates a Memento capturing the current content and returns it.
  • restore(memento) sets content back to whatever the given memento holds.

The Memento class is already written for you. It keeps the state in a private field and only hands it back through get_state, which is meant for the editor's own use.

Once this works, you can take a snapshot, keep editing, then jump back to exactly where you were.

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 = ""

    def save(self):
        """Capture the current content in a Memento and return it."""
        # TODO: create a Memento holding self.content and return it
        pass

    def restore(self, memento):
        """Set content back to the state stored in the given memento."""
        # TODO: read the memento's state and assign it to self.content
        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.