python-patterns icon indicating copy to clipboard operation
python-patterns copied to clipboard

memento example, why Transactional is defined as a descriptor?

Open LeiYangGH opened this issue 2 years ago • 2 comments

learning the example patterns/behavioral/memento.py. Transactional is defined as a descriptor, this looks more complicated

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

how about refactor to normal higher-order function?

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

LeiYangGH avatar May 17 '23 02:05 LeiYangGH

Sure, any simplification is welcome. Feel free to create a pull request

faif avatar May 23 '23 20:05 faif

created https://github.com/faif/python-patterns/pull/408. test passed. could you review?

LeiYangGH avatar May 24 '23 00:05 LeiYangGH