So I am learning exponential backoff, my code was running too fast and causing api limit errors I created this function and it works. but I want it once it is successful, attempts should be 0 again, right now every time theres an error it justs add one more to attempts and it stops after the 5 try. How can I make attempts =0 again once it is successful ?
Thank you for your help
def retry(func, retries=5):
def retry_wrapper(*args, **kwargs):
attempts = 0
while attempts < retries:
try:
return func(*args, **kwargs)
attempts = 0
except:
print(f'error {attempts}')
time.sleep(20)
attempts += 1
return retry_wrapper
Ok so there is something you need to know about the
return
method, once it is run, it doesn't run code after it, so if I have this:I will only get
hi
, nothello
, because the function stops running when return is called, its similar in a way tobreak
to escape a loop, so you need to put whatever you want to do before the return, always.So your code should look like this