Using decorator inside a function

Viewed 5882

Inside a function I'm using a retry mechanism like that (always in a try/except block):

        def load(self):
            [........]
            # Retry mechanism for locking database 
            for i in range(1, max_connection_retries+1):                        
                try:
                    cu.lock()
                    break
                except LockError as l_error:
                    if i < max_connection_retries:
                        sleep(20)
                        continue
                    else:
                        raise ContinuableError (logger.console(datetime.now().time().strftime ("%b %d %H:%M:%S") + ' ERROR:Impossible to lock the database after %i retries' % max_connection_retries))
        [.......]

I'm using this mechanism several times in others part of the same function and in other functions. It would be possible to apply a decorator to only this part of the code ? something like that:

        def load(self): 
            [.......]
            @retry(max=5,message='blablabla')                       
            try:
                cu.lock()
                break
            except LockError as l_error:

            [.......]

            @retry(max=5)                       
            try:
                cu.unlock()
                break
            except LockError as l_error:

If so, could you help me showing me an example of a decorator for doing such task ?

2 Answers
Related