Skip to content

Commit

Permalink
simplify patterns/behavioral/memento, changing Transactional from des…
Browse files Browse the repository at this point in the history
…criptor class to decorator method
  • Loading branch information
[email protected] committed May 24, 2023
1 parent d4b7f97 commit 76a5d21
Showing 1 changed file with 11 additions and 23 deletions.
34 changes: 11 additions & 23 deletions patterns/behavioral/memento.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,32 +41,20 @@ def rollback(self):
a_state()


class Transactional:
def Transactional(method):
"""Adds transactional semantics to methods. Methods decorated with
@Transactional will roll back to entry-state upon exceptions.
@Transactional will rollback to entry-state upon exceptions.
:param method: The function to be decorated.
"""

def __init__(self, method):
self.method = method

def __get__(self, obj, T):
"""
A decorator that makes a function transactional.
:param method: The function to be decorated.
"""

def transaction(*args, **kwargs):
state = memento(obj)
try:
return self.method(obj, *args, **kwargs)
except Exception as e:
state()
raise e

return transaction

def transaction(obj, *args, **kwargs):
state = memento(obj)
try:
return method(obj, *args, **kwargs)
except Exception as e:
state()
raise e
return transaction

class NumObj:
def __init__(self, value):
Expand Down

0 comments on commit 76a5d21

Please sign in to comment.