Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using decorator inside a function

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 ?

like image 661
psagrera Avatar asked Mar 22 '16 13:03

psagrera


People also ask

Can we use decorator inside a function in Python?

Nesting means placing or storing inside the other. Therefore, Nested Decorators means applying more than one decorator inside a function. Python allows us to implement more than one decorator to a function. It makes decorators useful for reusable building blocks as it accumulates the several effects together.

How do you call a decorator inside a function?

Inside Class A “fun1” Instance Method is calling the decorator function “Decorators” inside Class B “fun2”. Instance Method is calling the decorator function of Class A. To use the decorator of Class A, we must require using Class name in which decorator is present that's why we use “@A. Decorators” here.

Why do we use decorators with functions?

Decorators dynamically alter the functionality of a function, method, or class without having to directly use subclasses or change the source code of the function being decorated. Using decorators in Python also ensures that your code is DRY(Don't Repeat Yourself).

How do you use a decorator inside a class in Python?

To decorate a method in a class, first use the '@' symbol followed by the name of the decorator function. A decorator is simply a function that takes a function as an argument and returns yet another function.


1 Answers

The decorator syntax is just syntactic sugar for

# f could be a class as well
def f():
    ...
f = retry(f)

It cannot be applied to arbitrary anonymous blocks of code. The main purpose of a decorator is to rebind a name, and an anonymous block, by definition, has no name.

What you would need to do is refactor the code you want to retry into a function that gets decorated. For example,

@retry(max=5, message='blablabla')
def get_lock():
    try:
        cu.lock()
    except LockError as l_error:
        # Some action dependent on the implementation of retry


def load(self):
    get_lock()
like image 147
chepner Avatar answered Nov 05 '22 11:11

chepner