7.4. 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.

class Record:
    def __init__(self, firstname, lastname):
        self.firstname = firstname
        self.lastname = lastname

    def get_name(self):
        return (self.firstname, self.lastname)


class User:
    def __init__(self, firstname, lastname):
        self.firstname = firstname
        self.lastname = lastname
        self.history = []

    def __str__(self):
        return f'{self.firstname} {self.lastname}'

    def change_name(self, firstname, lastname):
        record = Record(self.firstname, self.lastname)
        self.history.append(record)
        self.firstname = firstname
        self.lastname = lastname

    def restore_name(self):
        record = self.history.pop()
        self.firstname, self.lastname = record.get_name()


def main():
    alice = User(firstname='Alice', lastname='Apricot')
    print(alice)
    # 'Alice Apricot'

    alice.change_name('Alice', 'Banana')
    print(alice)
    # 'Alice Banana'

    alice.restore_name()
    print(alice)
    # 'Alice Apricot'


main()
Alice Apricot
Alice Banana
Alice Apricot

7.4.1. 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

7.4.2. 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, '__str__')
>>> assert hasattr(User, 'change_name')
>>> assert hasattr(User, 'restore_name')

>>> alice = User(firstname='Alice', lastname='Apricot')
>>> print(alice)
Alice Apricot

>>> alice.change_name('Alice', 'Banana')
>>> print(alice)
Alice Banana

>>> alice.restore_name()
>>> print(alice)
Alice Apricot
"""

# %% 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, firstname, lastname):
        self.firstname = firstname
        self.lastname = lastname

    def __str__(self):
        return f'{self.firstname} {self.lastname}'

    def change_name(self, firstname, lastname):
        self.firstname = firstname
        self.lastname = lastname

    def restore_name(self):
        pass


# %% 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'

>>> 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