Memento Pattern in Python
Save snapshots of an object's state and restore them later, the idea behind undo and checkpoints.
- Originator, memento and caretaker
- Saving and restoring snapshots
- Keeping internals private
"final"current textSnapshot("draft")saved snapshotrestore() brings back "draft"
Snapshots you can roll back to
The problem
Undo, checkpoints in games and "restore defaults" all need to save an object's state and bring it back later, without other code reaching into the object's internals.
Think of it like this
The Memento pattern is like saving a game. The game creates a save file holding its state; you keep the save file without needing to understand what is inside. Later, loading the save puts the game back exactly where it was.
editor.save()💾 Create a save fileSnapshot(text)🔒 A sealed save that cannot be editededitor.text = "changed"🎮 Keep playing and change thingseditor.restore(saved)⏪ Load the save: back to draftThe Memento pattern captures an object's state in a snapshot object that can later restore it, without exposing the object's internal details to the code that stores the snapshot.
Key points
Snapshotis a frozen dataclass, so a saved snapshot cannot be changed afterwards.save()creates aSnapshotwith the current text.- The text is then changed to
"changed". restore(saved)puts the saved text back, so"draft"is printed.
When should you use it?
- Undo and redo in editors and drawing tools.
- Checkpoints and save games.
- Rolling back after a failed operation.
When not to use it
- Very large states saved often: snapshots use a lot of memory; store only the changes instead.
- Simple values: storing a copy of the variable is enough.
Example code
from dataclasses import dataclass
@dataclass(frozen=True)
class Snapshot:
# Memento: store a restorable snapshot without exposing internals.
text: str
class Editor:
def __init__(self): self.text = ""
def save(self): return Snapshot(self.text)
def restore(self, snapshot):
# Restore state without exposing representation details.
self.text = snapshot.text
editor = Editor()
editor.text = "draft"
saved = editor.save()
editor.text = "changed"
editor.restore(saved)
print(editor.text)
Result of running the code
draft
Code explanation
save() creates a Snapshot holding the editor's current text, and frozen=True stops anyone from changing that snapshot later. After the text is changed, restore(saved) copies the saved text back into the editor. The code that keeps saved never needs to know how the editor stores its state.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Replace the sample domain while preserving the pattern structure.
- Compare the pattern with a simpler implementation and explain the tradeoff.
- Write tests for each participant before adding another implementation.
Common mistakes
Saving a reference to mutable state
If the snapshot holds the same list the editor keeps changing, the saved state changes too.
def save(self):
return Snapshot(self.lines) # same list
def save(self):
return Snapshot(list(self.lines)) # a copy
Finished this lesson?
Mark it as learned to track your progress.