This is a static archive of the Python wiki, which was retired in February 2026 due to lack of usage and the resources necessary to serve it — predominately to bots, crawlers, and LLM companies.
Pages are preserved as they were at the time of archival. For current information, please visit python.org.
If a change to this archive is absolutely needed, requests can be made via the infrastructure@python.org mailing list.

The memento pattern is defined on wikipedia, and discussed on Ward's wiki under [MementoPattern].

The core intent is to capture an object's internal state (for later restoration) without violating encapsulation (i.e. uncovering internals for the purpose of externalization). Therefore, the state-representing object - called the memento - should satisfy 2 criteria:

  1. The memento should be opaque (aka provide no insight)
  2. The only allowed action with a memento is to return it to its originator for the purpose of state restoration. (This one may be relaxed in some variants to allow passing of states between sibling instances.)

Memento is extremely useful with transactional processing semantics, i.e. when an action is expected to either entirely succeed and change the system state in a defined way, or, on failure, not to change the system state at all.

A MementoClosure is a generic python implementation of the memento pattern. An example how to use the memento closure follows:

   1 # Perform a bunch of actions on object obj,
   2 # rollback to prior state on errors
   3 state = Memento(obj)
   4 try:
   5    obj.DoThis()
   6    obj.DoThat()
   7    myBigTransformer.Transform(obj)
   8 except:
   9    state() # restore captured state to obj
  10    raise   # re-raise exception knowing system state has not changed

Discussion


2026-02-14 16:09