## page was renamed from MementoPatternInPython #language en The memento pattern is defined on [[http://en.wikipedia.org/wiki/Memento_pattern|wikipedia]], and discussed on Ward's wiki under [Wiki: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) 1. 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 [[http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/413838|MementoClosure]] is a generic python implementation of the memento pattern. An example how to use the memento closure follows: {{{#!python # Perform a bunch of actions on object obj, # rollback to prior state on errors state = Memento(obj) try: obj.DoThis() obj.DoThat() myBigTransformer.Transform(obj) except: state() # restore captured state to obj raise # re-raise exception knowing system state has not changed }}} == Discussion ==