Unlocking Python's Secret Weapon: Snapshots and Undo with the Memento Pattern
This article explains how the Memento pattern lets a Python object save and restore its own state through opaque snapshots, why naive restores corrupt them, and when immutable state or commands are the better choice.
Undo, checkpoints before a risky operation and the ability to abandon an edit all require the same capability: recording the state of an object at one moment and returning to it later. Doing so naively exposes the internal attributes of the object to whatever code stores the copies, or produces copies that silently share data with the original. The present article examines the Memento pattern, in which the object itself produces an opaque snapshot of its state and later restores itself from it. A save slot in a game provides an appropriate image: before a difficult passage the player saves, and if the attempt fails the game reloads the whole situation as it was, while the save file itself is never edited by hand. This means that the originator, the object whose state matters, creates the memento and is the only party that reads it, while a third object, the caretaker, merely keeps mementos in order. The analogy, however, stops at this point, because a save file survives on disk after the game closes, whereas a memento lives in memory unless it is explicitly serialized. Returning an object to an earlier state without letting any other code depend on what that state contains is the secret weapon of this pattern.
Originator, Memento and Caretaker
The three roles divide the work cleanly: the originator knows its state, the memento holds a copy of it, and the caretaker decides when to save and when to restore without looking inside. In the following example, an editor is the originator, a frozen data class is the memento and a history object is the caretaker. The memento stores the list of tags as a tuple, so that neither the editor nor the caretaker can modify a snapshot after it has been taken.
from dataclasses import dataclass
@dataclass(frozen=True)
class EditorMemento:
text: str
cursor: int
tags: tuple
class Editor:
def __init__(self):
self.text, self.cursor, self.tags = "", 0, []
def write(self, fragment):
self.text = self.text[:self.cursor] + fragment + self.text[self.cursor:]
self.cursor += len(fragment)
def save(self):
return EditorMemento(self.text, self.cursor, tuple(self.tags))
def restore(self, memento):
self.text, self.cursor = memento.text, memento.cursor
self.tags = list(memento.tags)
class History:
def __init__(self, editor):
self.editor, self._snapshots = editor, []
def backup(self):
self._snapshots.append(self.editor.save())
def undo(self):
if self._snapshots:
self.editor.restore(self._snapshots.pop())
editor = Editor()
history = History(editor)
history.backup()
editor.write("Draft")
editor.tags.append("todo")
history.backup()
editor.write(" v2")
editor.tags.append("review")
history.undo()
print(editor.text, editor.cursor, editor.tags) # Output: Draft 5 ['todo']
history.undo()
print(repr(editor.text), editor.cursor, editor.tags) # Output: '' 0 []
The history never reads text, cursor or tags; it only stores and returns mementos, so the editor can add new attributes without any change in the caretaker. The restore builds a new list from the tuple, which prevents the editor from sharing a mutable object with the snapshot. Python does not enforce the opacity of the memento, since any code can read its fields; the pattern relies on the convention that only the originator does so.
Immutable State as Its Own Memento
When the state of an object is immutable, the object is already its own snapshot, and saving it costs a single reference. Frozen data classes, described in the article devoted to data classes, produce modified copies with dataclasses.replace, and Python 3.13 generalized the operation as copy.replace, which also accepts named tuples and any class that defines __replace__.
from dataclasses import dataclass, replace
@dataclass(frozen=True)
class Settings:
theme: str = "light"
font_size: int = 12
history = []
current = Settings()
history.append(current)
current = replace(current, theme="dark")
history.append(current)
current = replace(current, font_size=14)
print(current) # Output: Settings(theme='dark', font_size=14)
current = history.pop()
print(current) # Output: Settings(theme='dark', font_size=12)
No copying function is needed, because no version of the settings is ever modified after it is created; each change produces a new object, and the history keeps references to the old ones. Fields that hold mutable containers break this guarantee, so an immutable design also uses tuples and frozen sets inside the object.
Memento and Command
This section compares the Memento pattern with the Command pattern, examined in the article devoted to the Command pattern, since both support undo by different means. A command records only what it changed and reverses that change, so its cost is proportional to the size of the change; a memento records the whole state, so its cost is proportional to the size of the object, but restoring it never depends on reversing each operation correctly. The two are often combined: a command that cannot compute its own inverse takes a memento of the originator before executing and restores it in undo.
Pitfalls of the Memento Pattern
A memento is only as reliable as the copy that it holds and the restore that reads it, so most of its errors concern copying. Six pitfalls are distinguished, which are the following:
- Restoring shared objects. Assigning the objects of the memento to the originator makes them shared, so the next change to the originator also changes the snapshot.
- Attributes that survive the restore. Updating
__dict__with the saved values leaves in place every attribute added after the snapshot was taken. - Objects without
__dict__. A snapshot built fromself.__dict__fails on classes that declare__slots__, which store their attributes elsewhere, as described in the article devoted to__slots__. - Shallow copies of nested state. A shallow copy of a dictionary of lists shares the lists, which reproduces the first pitfall one level deeper.
- Unbounded memory. Every snapshot holds a full copy of the state; a long history needs a limit, or commands that store differences.
- State that cannot be copied. Open files, sockets and locks cannot be deep-copied, as
copy.deepcopy(threading.Lock())raisesTypeError; the memento must record a description of such resources, not the resources themselves.
The first two pitfalls are reproduced in the following example, with the restore used by many tutorials and a corrected version.
import copy
class Note:
def __init__(self):
self.tags = []
def save(self):
return copy.deepcopy(self.__dict__)
def restore(self, state):
self.__dict__.update(state)
class SafeNote(Note):
def restore(self, state):
self.__dict__.clear()
self.__dict__.update(copy.deepcopy(state))
for cls in (Note, SafeNote):
note = cls()
snapshot = note.save()
note.restore(snapshot)
note.tags.append("urgent")
note.pinned = True
note.restore(snapshot)
print(cls.__name__, snapshot["tags"], hasattr(note, "pinned"))
# Output: Note ['urgent'] True
# Output: SafeNote [] False
In the first class, the list appended to after the restore is the very list stored in the snapshot, so the snapshot is corrupted, and the attribute pinned remains after a restore that should have removed it. The corrected restore removes every current attribute and installs a fresh copy of the saved state, so the same memento can be restored any number of times.
Choosing How to Save State
Consequently, the right technique depends on the size of the state, on whether it is mutable and on how undo must behave, as the following table summarizes.
| Situation | Recommended approach |
|---|---|
| Immutable state | Keep references to old versions; dataclasses.replace or copy.replace |
| Small mutable state with private details | A memento created and read only by the originator |
| Large state with small changes | Commands that record and reverse each change |
| An operation whose inverse is hard to compute | A command that stores a memento before executing |
| A long editing session | A bounded history, for example a deque with maxlen |
| State that includes files, sockets or locks | A memento that records how to reopen them |
Conclusion
It is concluded that the Memento pattern lets an object return to an earlier state through snapshots that it alone creates and reads, while a caretaker stores them without depending on their contents, and that in Python the snapshots are most reliable when they are immutable. This magic depends on copying at both ends, when saving and when restoring, on removing attributes that did not exist in the snapshot and on bounding the number of snapshots kept. Creating new objects by copying a fully configured instance, instead of building each one from its constructor, is the purpose of the Prototype pattern, which is developed in a future article of this series.