Hey everybody I\'m working on a data scraping project and I\'m looking for a clean way to repeat a function call if an exception is raised.
Pseudo-code:
To raise Exception as usual after n retries
from functools import wraps
def retry(times):
"""
Decorator to retry any functions 'times' times.
"""
def retry_decorator(func):
@wraps(func)
def retried_function(*args, **kwargs):
for i in range(times - 1):
try:
func(*args, **kwargs)
return
except Exception:
pass
func(*args, **kwargs)
return retried_function
return retry_decorator
# test
attempts = 3
@retry(4)
def function_that_raises_error():
global attempts
if 0 < attempts:
print("fail")
attempts -= 1
raise Exception
print("pass")
function_that_raises_error()