5.3. Memento
Undo operation
Remembering state of objects
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.
5.3.1. Problem
>>> class User:
... def __init__(self, username, password):
... self.username = username
... self.password = password
...
... def set_password(self, new_password):
... self.password = new_password
Usage:
>>> alice = User(username='alice', password='secret')
>>>
>>> alice.password
'secret'
>>>
>>> alice.set_password('qwerty')
>>>
>>> alice.password
'qwerty'
But, there is no way to undo the last operation.
5.3.2. Solution
>>> from datetime import datetime, timezone
>>>
>>>
>>> class State:
... def __init__(self, cls, data):
... self.since = datetime.now(tz=timezone.utc)
... self.cls = cls
... self.data = data
...
... def __repr__(self):
... clsname = self.cls.__name__
... return f'<State on={self.since}, data={self.data}>'
>>>
>>>
>>> class User:
... def __init__(self, username, password):
... self.username = username
... self.password = password
... self._history = []
...
... def set_password(self, new_password):
... self.save()
... self.password = new_password
...
... def save(self):
... data = {'username': self.username, 'password': self.password}
... state = State(cls=self.__class__, data=data)
... self._history.append(state)
...
... def undo(self):
... if not self._history:
... raise ValueError('No history to undo')
... state = self._history.pop()
... self.username = state.data['username']
... self.password = state.data['password']
Usage:
>>> alice = User(username='alice', password='secret')
>>>
>>> alice.password
'secret'
>>>
>>> alice.set_password('qwerty')
>>> alice.password
'qwerty'
>>>
>>> alice._history
[<State on=2025-04-11 13:34:43.774463+00:00, data={'username': 'alice', 'password': 'secret'}>]
>>>
>>> alice.undo()
>>> alice.password
'secret'
5.3.3. Case Study

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
5.3.4. Use Case - 1
>>> from dataclasses import dataclass, field
>>>
>>>
>>> @dataclass(frozen=True)
... class Transaction:
... amount: float
... when: datetime = field(default_factory=datetime.now)
>>>
>>>
>>> @dataclass
... class History:
... transactions: list[Transaction] = field(default_factory=list)
...
... def push(self, transaction: Transaction) -> None:
... self.transactions.append(transaction)
...
... def pop(self) -> Transaction:
... return self.transactions.pop()
>>>
>>>
>>> @dataclass
... class Account:
... balance: float = 0.0
... history: History = field(default_factory=History)
...
... def deposit(self, amount: float) -> None:
... transaction = Transaction(amount)
... self.balance += transaction.amount
... self.history.push(transaction)
...
... def undo(self):
... transaction = self.history.pop()
... self.balance -= transaction.amount
Usage:
>>> account = Account()
>>>
>>> account.deposit(100.00)
>>> account.balance
100.0
>>>
>>> account.deposit(50.00)
>>> account.balance
150.0
>>>
>>> account.undo()
>>> account.balance
100.0
5.3.5. Assignments
# %% About
# - Name: DesignPatterns Behavioral Memento
# - Difficulty: easy
# - Lines: 11
# - Minutes: 13
# %% 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
# %% English
# 1. Modify class User
# 2. Add functionality to remember and restore
# firstname and lastname changes
# 3. Implement Memento pattern
# 4. Run doctests - all must succeed
# %% Polish
# 1. Zmodyfikuj klasę User
# 2. Dodaj funkcjonalność zapamiętywania i przywracania
# zmian imienia i nazwiska
# 3. Zaimplementuj wzorzec Pamiątka
# 4. Uruchom doctesty - wszystkie muszą się powieść
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> from inspect import isclass, ismethod
>>> assert isclass(User)
>>> assert hasattr(User, '__init__')
>>> assert hasattr(User, 'set_password')
>>> assert hasattr(User, 'undo')
>>> alice = User(username='alice', password='secret')
>>> assert alice.password == 'secret'
>>> alice.set_password('qwerty')
>>> assert alice.password == 'qwerty'
>>> alice.undo()
>>> assert alice.password == 'secret'
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% Imports
# %% Types
from typing import Callable, List, Any
User: type
UserMemento: type
History: type
create_memento: Callable[[object], object]
restore_from_memento: Callable[[object, object], None]
save: Callable[[object, object], None]
undo: Callable[[object], object]
# %% Data
# %% Result
class User:
def __init__(self, username, password):
self.username = username
self.password = password
def set_password(self, new_password):
self.password = new_password
def undo(self):
raise NotImplementedError
# %% About
# - Name: DesignPatterns Behavioral Memento
# - Difficulty: medium
# - Lines: 29
# - Minutes: 13
# %% 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
# %% 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ść
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> from inspect import isclass
>>> assert isclass(Account)
>>> assert hasattr(Account, '__init__')
>>> assert hasattr(Account, 'deposit')
>>> assert hasattr(Account, 'balance')
>>> assert hasattr(Account, 'undo')
>>> 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
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% Imports
from dataclasses import dataclass, field
from datetime import datetime
# %% Types
Account: type
Transaction: type
History: type
# %% Data
# %% Result
@dataclass
class Account:
balance: float = 0.0
def deposit(self, amount: float) -> None:
raise NotImplementedError
def undo(self):
raise NotImplementedError