BehavioralPythonverifiedVerified

Memento Pattern in Python

Captures and externalizes an object's internal state without violating encapsulation, allowing the object to be restored to that state later.

How to Implement the Memento Pattern in Python

1Step 1: Define the Memento that captures editor state

from dataclasses import dataclass


@dataclass(frozen=True)
class EditorMemento:
    content: str
    cursor: int

2Step 2: Implement the Editor with save and restore

class Editor:
    def __init__(self) -> None:
        self._content = ""
        self._cursor = 0

    def type_text(self, text: str) -> None:
        self._content = (
            self._content[: self._cursor]
            + text
            + self._content[self._cursor :]
        )
        self._cursor += len(text)

    def save(self) -> EditorMemento:
        return EditorMemento(self._content, self._cursor)

    def restore(self, memento: EditorMemento) -> None:
        self._content = memento.content
        self._cursor = memento.cursor

    def __str__(self) -> str:
        return f'"{self._content}" (cursor: {self._cursor})'

3Step 3: Create a History caretaker to manage snapshots

class History:
    def __init__(self) -> None:
        self._mementos: list[EditorMemento] = []

    def push(self, memento: EditorMemento) -> None:
        self._mementos.append(memento)

    def pop(self) -> EditorMemento | None:
        return self._mementos.pop() if self._mementos else None

4Step 4: Take snapshots and undo changes

editor = Editor()
history = History()

history.push(editor.save())
editor.type_text("Hello")
history.push(editor.save())
editor.type_text(", World")

print(editor)  # "Hello, World" (cursor: 12)

editor.restore(history.pop())
print(editor)  # "Hello" (cursor: 5)

editor.restore(history.pop())
print(editor)  # "" (cursor: 0)

Memento Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Memento Pattern in the Real World

Think of a video game save point. When you save, the game (originator) packages your character's stats, inventory, and position into a save file (memento). The save system (caretaker) stores these files without understanding their contents. When you die and reload, the save file is handed back to the game, which restores everything exactly as it was.