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 ?
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.
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.
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).
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With