In Python try until no error In Python try until no error python python

In Python try until no error


It won't get much cleaner. This is not a very clean thing to do. At best (which would be more readable anyway, since the condition for the break is up there with the while), you could create a variable result = None and loop while it is None. You should also adjust the variables and you can replace continue with the semantically perhaps correct pass (you don't care if an error occurs, you just want to ignore it) and drop the break - this also gets the rest of the code, which only executes once, out of the loop. Also note that bare except: clauses are evil for reasons given in the documentation.

Example incorporating all of the above:

result = Nonewhile result is None:    try:        # connect        result = get_data(...)    except:         pass# other code that uses result but is not involved in getting it


Here is one that hard fails after 4 attempts, and waits 2 seconds between attempts. Change as you wish to get what you want form this one:

from time import sleepfor x in range(0, 4):  # try 4 times    try:        # msg.send()        # put your logic here        str_error = None    except Exception as str_error:        pass    if str_error:        sleep(2)  # wait for 2 seconds before trying to fetch the data again    else:        break

Here is an example with backoff:

from time import sleepsleep_time = 2num_retries = 4for x in range(0, num_retries):      try:        # put your logic here        str_error = None    except Exception as str_error:        pass    if str_error:        sleep(sleep_time)  # wait before trying to fetch the data again        sleep_time *= 2  # Implement your backoff algorithm here i.e. exponential backoff    else:        break


Maybe something like this:

connected = Falsewhile not connected:    try:        try_connect()        connected = True    except ...:        pass