8.4. Memento
EN: Memento
PL: Pamiątka
Type: object
The Memento design pattern is a behavioral design pattern that allows an object to save and restore its previous state. This is useful when you need to provide some sort of undo functionality in your application.
In Python, we can implement the Memento pattern using classes. Here's a simple example:
First, we define a Memento
class that will hold the state of the
Originator
:
>>> class Memento:
... def __init__(self, state):
... self._state = state
...
... def get_saved_state(self):
... return self._state
Then, we define an Originator
class that has a state and creates a memento
object to save its state:
>>> class Originator:
... _state = ""
...
... def set(self, state):
... print(f"Originator: Setting state to {state}")
... self._state = state
...
... def save_to_memento(self):
... print("Originator: Saving to Memento.")
... return Memento(self._state)
...
... def restore_from_memento(self, memento):
... self._state = memento.get_saved_state()
... print(f"Originator: State after restoring from Memento: {self._state}")
Next, we define a Caretaker
class that keeps track of multiple mementos:
>>> class Caretaker:
... def __init__(self):
... self._saved_states = []
...
... def add_memento(self, memento):
... self._saved_states.append(memento)
...
... def get_memento(self, index):
... return self._saved_states[index]
Finally, we can use the Originator
, Memento
, and Caretaker
classes
like this:
>>> caretaker = Caretaker()
>>> originator = Originator()
>>>
>>> originator.set("State1")
Originator: Setting state to State1
>>> originator.set("State2")
Originator: Setting state to State2
>>> caretaker.add_memento(originator.save_to_memento())
Originator: Saving to Memento.
>>>
>>> originator.set("State3")
Originator: Setting state to State3
>>> caretaker.add_memento(originator.save_to_memento())
Originator: Saving to Memento.
>>>
>>> originator.set("State4")
Originator: Setting state to State4
>>> originator.restore_from_memento(caretaker.get_memento(0))
Originator: State after restoring from Memento: State2
>>> originator.restore_from_memento(caretaker.get_memento(1))
Originator: State after restoring from Memento: State3
In this example, the Originator
sets and changes its state. It can also
create a Memento
that represents its current state. The Caretaker
can
keep track of these mementos and restore the Originator
to its previous
states.
8.4.1. Pattern
Undo operation
Remembering state of objects
8.4.2. Problem
8.4.3. Solution
from dataclasses import dataclass, field
@dataclass(frozen=True)
class EditorState:
content: str
@dataclass
class History:
states: list[EditorState] = field(default_factory=list)
def push(self, state: EditorState) -> None:
self.states.append(state)
def pop(self) -> EditorState:
return self.states.pop()
class Editor:
content: str
def set_content(self, content: str) -> None:
self.content = content
def get_content(self) -> str:
return self.content
def create_state(self):
return EditorState(self.content)
def restore_state(self, state: EditorState):
self.content = state.content
if __name__ == '__main__':
editor = Editor()
history = History()
editor.set_content('a')
print(editor.content)
# a
editor.set_content('b')
history.push(editor.create_state())
print(editor.content)
# b
editor.set_content('c')
print(editor.content)
# c
editor.restore_state(history.pop())
print(editor.content)
# b
8.4.4. Assignments
# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% About
# - Name: DesignPatterns Behavioral Memento
# - Difficulty: medium
# - Lines: 29
# - Minutes: 13
# %% English
# 1. Implement Memento pattern
# 2. Create account history of transactions with:
# - `when: datetime` - date and time of a transaction
# - `amount: float` - transaction amount
# 3. Allow for transaction undo
# 4. Run doctests - all must succeed
# %% Polish
# 1. Zaimplementuj wzorzec Memento
# 2. Stwórz historię transakcji na koncie z:
# - `when: datetime` - data i czas transakcji
# b: `amount: float` - kwota transakcji
# 3. Pozwól na wycofywanie (undo) transakcji
# 4. Uruchom doctesty - wszystkie muszą się powieść
# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> account = Account()
>>> account.deposit(100.00)
>>> account.balance
100.0
>>> account.deposit(50.00)
>>> account.balance
150.0
>>> account.deposit(25.00)
>>> account.balance
175.0
>>> account.undo()
>>> account.balance
150.0
"""
from dataclasses import dataclass, field
from datetime import datetime
@dataclass
class Account:
balance: float = 0.0
def deposit(self, amount: float) -> None:
raise NotImplementedError
def undo(self):
raise NotImplementedError