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, firstname, lastname):
...         self.firstname = firstname
...         self.lastname = lastname
...
...     def set_name(self, firstname, lastname):
...         self.firstname = firstname
...         self.lastname = lastname
>>>
>>>
>>> myuser = User('Alice', 'Apricot')
>>> vars(myuser)
{'firstname': 'Alice', 'lastname': 'Apricot'}
>>>
>>> myuser.set_name('Bob', 'Blackthorn')
>>> vars(myuser)
{'firstname': 'Bob', 'lastname': 'Blackthorn'}

But, there is no way to undo the last operation.

5.3.2. Solution

>>> class User:
...     def __init__(self, firstname, lastname):
...         self.firstname = firstname
...         self.lastname = lastname
...         self._changelog = []
...
...     def commit(self):
...         state = self.__dict__.copy()
...         state.pop('_changelog')
...         self._changelog.append(state)
...
...     def undo(self):
...         state = self._changelog.pop()
...         self.__dict__.update(state)
...
...     def set_name(self, firstname, lastname):
...         self.commit()
...         self.firstname = firstname
...         self.lastname = lastname
>>>
>>>
>>> myuser = User('Alice', 'Apricot')
>>> vars(myuser)
{'firstname': 'Alice', 'lastname': 'Apricot', '_changelog': []}
>>>
>>> myuser.set_name('Bob', 'Blackthorn')
>>> vars(myuser)
{'firstname': 'Bob', 'lastname': 'Blackthorn', '_changelog': [{'firstname': 'Alice', 'lastname': 'Apricot'}]}
>>>
>>> myuser.undo()
>>> vars(myuser)
{'firstname': 'Alice', 'lastname': 'Apricot', '_changelog': []}

5.3.3. Attach Information

>>> from datetime import datetime, timezone
>>> from uuid import uuid4
>>>
>>>
>>> class User:
...     def __init__(self, firstname, lastname):
...         self.firstname = firstname
...         self.lastname = lastname
...         self._changelog = []
...
...     def commit(self):
...         state = self.__dict__.copy()
...         state.pop('_changelog')
...         snapshot = {
...             'timestamp': datetime.now(timezone.utc),
...             'uuid': uuid4(),
...             'state': state}
...         self._changelog.append(snapshot)
...
...     def undo(self):
...         if not self._changelog:
...             raise IndexError('No states to undo')
...         snapshot = self._changelog.pop()
...         self.__dict__.update(snapshot['state'])
...
...     def set_name(self, firstname, lastname):
...         self.commit()
...         self.firstname = firstname
...         self.lastname = lastname
>>>
>>>
>>> myuser = User('Alice', 'Apricot')
>>> vars(myuser)
{'firstname': 'Alice', 'lastname': 'Apricot', '_changelog': []}
>>>
>>> myuser.set_name('Bob', 'Blackthorn')
>>> vars(myuser)
{'firstname': 'Bob', 'lastname': 'Blackthorn', '_changelog': [
    {'timestamp': datetime.datetime(2025, 12, 5, 11, 10, 38, 119782, tzinfo=datetime.timezone.utc), 'uuid': UUID('c9cb66e1-8575-4439-964c-54e0a6bdbd86'), 'state': {'firstname': 'Alice', 'lastname': 'Apricot'}}
]}
>>>
>>> myuser.set_name('Carol', 'Corn')
>>> vars(myuser)
{'firstname': 'Carol', 'lastname': 'Corn', '_changelog': [
    {'timestamp': datetime.datetime(2025, 12, 5, 11, 10, 38, 119782, tzinfo=datetime.timezone.utc), 'uuid': UUID('c9cb66e1-8575-4439-964c-54e0a6bdbd86'), 'state': {'firstname': 'Alice', 'lastname': 'Apricot'}},
    {'timestamp': datetime.datetime(2025, 12, 5, 11, 10, 57, 223688, tzinfo=datetime.timezone.utc), 'uuid': UUID('31168fb1-c2f1-4f70-a783-cace104911f3'), 'state': {'firstname': 'Bob', 'lastname': 'Blackthorn'}}
]}
>>>
>>> myuser.undo()
>>> vars(myuser)
{'firstname': 'Bob', 'lastname': 'Blackthorn', '_changelog': [
    {'timestamp': datetime.datetime(2025, 12, 5, 11, 10, 38, 119782, tzinfo=datetime.timezone.utc), 'uuid': UUID('c9cb66e1-8575-4439-964c-54e0a6bdbd86'), 'state': {'firstname': 'Alice', 'lastname': 'Apricot'}}
]}
>>>
>>> myuser.undo()
>>> vars(myuser)
{'firstname': 'Alice', 'lastname': 'Apricot', '_changelog': []}

5.3.4. Case Study

../../_images/designpatterns-memento-solution.png
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.5. Use Case - 1

>>> from dataclasses import dataclass, field
>>> from datetime import datetime, timezone
>>> from pprint import pprint
>>>
>>>
>>> @dataclass(frozen=True)
... class State:
...     timestamp: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
...     uuid: str = field(default_factory=uuid4)
...     data: dict | None = None
>>>
>>>
>>> @dataclass
... class Memento:
...     _changelog: list[State] = field(default_factory=list)
...
...     def _commit(self):
...         current_state = self.__dict__.copy()
...         current_state.pop('_changelog')
...         state = State(data=current_state)
...         self._changelog.append(state)
...
...     def _rollback(self):
...         if not self._changelog:
...             raise IndexError('No states to rollback')
...         previous_state = self._changelog.pop()
...         self.__dict__.update(previous_state.data)
>>>
>>>
>>> @dataclass
... class Account(Memento):
...     balance: float = 0.0
...
...     def deposit(self, amount: float) -> None:
...         self._commit()
...         self.balance += amount
...
...     def undo(self):
...         self._rollback()
>>>
>>>
>>> myaccount = Account()
>>>
>>> myaccount.deposit(100.00)
>>> myaccount.deposit(50.00)
>>> myaccount.balance
150.0
>>>
>>> pprint(myaccount._changelog)
[State(timestamp=datetime.datetime(2025, 12, 5, 11, 41, 54, 849134, tzinfo=datetime.timezone.utc),
       uuid=UUID('f9067675-cd45-4897-a986-95fb0b902995'),
       data={'balance': 0.0}),
 State(timestamp=datetime.datetime(2025, 12, 5, 11, 41, 54, 849785, tzinfo=datetime.timezone.utc),
       uuid=UUID('ee0d1ff4-cb64-4403-92fb-ddc7f23c966c'),
       data={'balance': 100.0})]
>>>
>>> myaccount.undo()
>>> myaccount.balance
100.0
>>>
>>> pprint(myaccount._changelog)
[State(timestamp=datetime.datetime(2025, 12, 5, 11, 41, 54, 849134, tzinfo=datetime.timezone.utc),
       uuid=UUID('f9067675-cd45-4897-a986-95fb0b902995'),
       data={'balance': 0.0})]
>>>
>>> myaccount.undo()
>>> myaccount.balance
0.0
>>>
>>> pprint(myaccount._changelog)
[]
>>>
>>> myaccount.undo()
Traceback (most recent call last):
IndexError: No states to rollback

5.3.6. Use Case - 2

>>> class Snapshot:
...     def __init__(self, data):
...         self.timestamp = datetime.now(timezone.utc)
...         self.uuid = uuid4()
...         self.data = data
...
...     def __repr__(self):
...         uuid = f'{self.uuid.hex:.7}'
...         timestamp = f'{self.timestamp:%Y-%m-%d %H:%M:%S}'
...         return f'<Snapshot {uuid} @ {timestamp} {self.data}>'
>>>
>>>
>>> class History:
...     def __init__(self):
...         self.snapshots = []
...
...     def __repr__(self):
...         return str(self.snapshots)
...
...     def commit(self, data):
...         snapshot = Snapshot(data)
...         self.snapshots.append(snapshot)
...
...     def restore(self):
...         if not self.snapshots:
...             raise IndexError('No snapshots to restore')
...         snapshot = self.snapshots.pop()
...         return snapshot.data
>>>
>>>
>>> class Account:
...     def __init__(self):
...         self.balance = 0.0
...         self._history = History()
...
...     def deposit(self, amount: float) -> None:
...         self._history.commit({'balance': self.balance})
...         self.balance += amount
...
...     def undo(self):
...         snapshot = self._history.restore()
...         self.balance = snapshot['balance']
>>>
>>>
>>> myaccount = Account()
>>>
>>> myaccount.deposit(100.00)
>>> myaccount.deposit(50.00)
>>> myaccount.deposit(10.00)
>>> myaccount.balance
160.0
>>>
>>> pprint(myaccount._history)
[<Snapshot 4f8f2ca @ 2025-12-05 12:23:36 {'balance': 0.0}>,
 <Snapshot a3fa8ea @ 2025-12-05 12:23:36 {'balance': 100.0}>,
 <Snapshot ccd08ca @ 2025-12-05 12:23:36 {'balance': 150.0}>]
>>>
>>>
>>> myaccount.undo()
>>> myaccount.balance
150.0
>>>
>>> pprint(myaccount._history)
[<Snapshot 4f8f2ca @ 2025-12-05 12:23:36 {'balance': 0.0}>,
 <Snapshot a3fa8ea @ 2025-12-05 12:23:36 {'balance': 100.0}>]
>>>
>>> myaccount.undo()
>>> myaccount.balance
100.0
>>>
>>> pprint(myaccount._history)
[<Snapshot 4f8f2ca @ 2025-12-05 12:23:36 {'balance': 0.0}>]
>>>
>>> myaccount.undo()
>>> myaccount.balance
0.0
>>>
>>> pprint(myaccount._history)
[]
>>>
>>> myaccount.undo()
Traceback (most recent call last):
IndexError: No snapshots to restore

5.3.7. 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 password changes
# 3. Implement Memento pattern
# 4. Run doctests - all must succeed

# %% Polish
# 1. Zmodyfikuj klasę User
# 2. Dodaj funkcjonalność zapamiętywania i przywracania zmian hasła
# 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 has an is invalid version; expected: `3.9` or newer.'

>>> from inspect import isclass, ismethod

>>> assert isclass(User), \
'Object `User` has an invalid type; expected: `class`.'

>>> assert hasattr(User, '__init__'), \
'Class `User` has an invalid attribute; expected: to have an attribute `__init__`.'

>>> assert hasattr(User, 'set_password'), \
'Class `User` has an invalid attribute; expected: to have an attribute `set_password`.'

>>> assert hasattr(User, 'undo'), \
'Class `User` has an invalid attribute; expected: to have an attribute `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 -f -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:
#    - `timestamp: 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:
#    - `timestamp: datetime` - data i czas transakcji
#    - `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 has an is invalid version; expected: `3.9` or newer.'

>>> from inspect import isclass
>>> assert isclass(Account), \
'Object `Account` has an invalid type; expected: `class`.'

>>> assert hasattr(Account, '__init__'), \
'Object `Account` has an invalid attribute; expected: to have an attribute `__init__`.'

>>> assert hasattr(Account, 'deposit'), \
'Object `Account` has an invalid attribute; expected: to have an attribute `deposit`.'

>>> assert hasattr(Account, 'balance'), \
'Object `Account` has an invalid attribute; expected: to have an attribute `balance`.'

>>> assert hasattr(Account, 'undo'), \
'Object `Account` has an invalid attribute; expected: to have an attribute `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 -f -v myfile.py`

# %% Imports
from dataclasses import dataclass, field
from datetime import datetime
from uuid import uuid4

# %% Types
Account: type
Transaction: type
History: type

# %% Data

# %% Result
@dataclass
class Account:
    balance: float = 0.0

    def deposit(self, amount: float) -> None:
        self.balance += amount

    def undo(self):
        raise NotImplementedError