Python Design Patterns

Memento Pattern in Python

Memento supports undo and checkpoints by storing snapshots that only the originator interprets.

What is Memento Pattern?

Memento supports undo and checkpoints by storing snapshots that only the originator interprets.

Capture and restore an object's state without exposing its internals.

When should you use it?

  • Solve recurring object-design problems with proven structures.
  • Decouple responsibilities so code is easier to extend and test.
  • Use shared design vocabulary when discussing architecture with a team.

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)

Expected output

draft

How it works

Editor saves an immutable text snapshot and later restores it after further edits.

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 Python IDE →