Python Design Patterns

Memento Pattern in Python

Save snapshots of an object's state and restore them later, the idea behind undo and checkpoints.

  • Advanced
  • 3 min read
  • 1 runnable example
What you'll learn
  • Originator, memento and caretaker
  • Saving and restoring snapshots
  • Keeping internals private
Editor history
  1. "final"current text
  2. Snapshot("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.

From saving a game to code
editor.save()💾 Create a save file
Snapshot(text)🔒 A sealed save that cannot be edited
editor.text = "changed"🎮 Keep playing and change things
editor.restore(saved)⏪ Load the save: back to draft
Save a snapshot, change things, restore the snapshot.
In one sentence

The 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

  1. Snapshot is a frozen dataclass, so a saved snapshot cannot be changed afterwards.
  2. save() creates a Snapshot with the current text.
  3. The text is then changed to "changed".
  4. 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

Run code →
main.py
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)
Get a Run button for this example

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.

  1. Replace the sample domain while preserving the pattern structure.
  2. Compare the pattern with a simpler implementation and explain the tradeoff.
  3. Write tests for each participant before adding another implementation.
Run in the Python compiler →

Common mistakes

Saving a reference to mutable state

If the snapshot holds the same list the editor keeps changing, the saved state changes too.

Problem
def save(self):
    return Snapshot(self.lines)  # same list
Fix
def save(self):
    return Snapshot(list(self.lines))  # a copy

Finished this lesson?

Mark it as learned to track your progress.