From 76a5d217e078dc8ba423396fc73592eae253349d Mon Sep 17 00:00:00 2001 From: "yang.lei@cerence.com" Date: Wed, 24 May 2023 08:51:00 +0800 Subject: [PATCH] simplify patterns/behavioral/memento, changing Transactional from descriptor class to decorator method --- patterns/behavioral/memento.py | 34 +++++++++++----------------------- 1 file changed, 11 insertions(+), 23 deletions(-) diff --git a/patterns/behavioral/memento.py b/patterns/behavioral/memento.py index e1d42fc2..d4d13325 100644 --- a/patterns/behavioral/memento.py +++ b/patterns/behavioral/memento.py @@ -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):