Memento Pattern Implementation in Python
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Memento Pattern runs in O(1) time and O(n) space, in Python as in every other language.
- ✓copy.deepcopy is the general snapshot and honours __deepcopy__ with its memo dictionary so cycles and shared references are preserved.
- ✓Define __getstate__ to exclude caches, file handles and locks rather than snapshotting the whole __dict__, which is both smaller and correct.
- ✓The Python trap: pickle executes arbitrary code during loading: the format includes opcodes that call importable objects, so unpickling data an attacker can influence is remote code execution, and the standard library documentation states plainly that pickle is not secure.
- ✓deepcopy is implemented in Python with a per-type dispatch and a memo dictionary, so it is commonly one to two orders of magnitude slower than constructing the object directly, and a snapshot per user action in a hot editor is felt.
What Memento Pattern actually is
Memento Pattern in Python: what you actually reach for
Python implementation
import copy
from dataclasses import dataclass
@dataclass(frozen=True) # a captured memento must not be editable
class Memento:
text: str
cursor: int
class Editor:
def __init__(self) -> None:
self.text, self.cursor = "", 0
self._cache: dict = {} # must NOT be snapshotted
# Snapshot exactly what matters, not self.__dict__.
def save(self) -> Memento:
return Memento(self.text, self.cursor)
def restore(self, m: Memento) -> None:
self.text, self.cursor = m.text, m.cursor
self._cache.clear()
def __getstate__(self) -> dict:
s = self.__dict__.copy()
del s["_cache"] # caches and handles never serialise well
return s
# pickle EXECUTES code on load: never unpickle data you did not write.
# Use json for a memento log that touches disk or a network.
import json
history = [Editor().save()]
json.dumps([m.__dict__ for m in history])Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Python-specific trap
Performance in Python, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Python type or library should I use for Memento Pattern?
copy.deepcopy is the general snapshot and honours __deepcopy__ with its memo dictionary so cycles and shared references are preserved. The pickle protocol hooks, __getstate__ and __setstate__, let a class define exactly what a snapshot contains, and since Python 3.11 __getstate__ has a default implementation on object. dataclasses.replace and, from 3.13, copy.replace produce a modified copy. For on-disk checkpoints, json is safe and pickle is not.
What is the most common Python mistake when implementing Memento Pattern?
pickle executes arbitrary code during loading: the format includes opcodes that call importable objects, so unpickling data an attacker can influence is remote code execution, and the standard library documentation states plainly that pickle is not secure. A memento stack persisted with pickle and reloaded from disk is exactly that situation if the file is ever writable by another user or arrives over a network. The second trap is quieter: deepcopy follows every reachable reference, so snapshotting one object that holds a link to a parent registry silently copies the entire object graph and the snapshot is enormous.
How does Memento Pattern actually perform in Python?
deepcopy is implemented in Python with a per-type dispatch and a memo dictionary, so it is commonly one to two orders of magnitude slower than constructing the object directly, and a snapshot per user action in a hot editor is felt. Defining __getstate__ to return a small tuple of primitives makes both the copy and any later serialisation dramatically cheaper. Storing deltas rather than full snapshots turns memory from O(history times state) into O(total change), which is the usual fix once history is long. Time complexity is O(1) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for Replit, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.