🤖📘🍻 Hooray! After 3 years of work, we've finally released a new ebook on design patterns! Check it out »

Memento Design Pattern in Python

Capture and externalize an object's internal state so that the object
can be restored to this state later, without violating encapsulation.

import pickle

class Originator:
    Create a memento containing a snapshot of its current internal
    Use the memento to restore its internal state.

    def __init__(self):
        self._state = None

    def set_memento(self, memento):
        previous_state = pickle.loads(memento)

    def create_memento(self):
        return pickle.dumps(vars(self))

def main():
    originator = Originator()
    memento = originator.create_memento()
    originator._state = True

if __name__ == "__main__":

Code examples

More info, diagrams and examples of the Memento design pattern you can find on our new partner resource Refactoring.Guru.