How to retry after exception?
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: The Builders
--
Chapters
00:00 Question
00:39 Accepted answer (Score 531)
00:59 Answer 2 (Score 318)
01:21 Answer 3 (Score 108)
02:05 Answer 4 (Score 48)
02:27 Thank you
--
Full question
https://stackoverflow.com/questions/2083...
Answer 2 links:
[github.com/jd/tenacity]: https://github.com/jd/tenacity
[github.com/litl/backoff]: https://github.com/litl/backoff
[retrying package]: https://pypi.python.org/pypi/retrying
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #loops #exception #tryexcept
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: The Builders
--
Chapters
00:00 Question
00:39 Accepted answer (Score 531)
00:59 Answer 2 (Score 318)
01:21 Answer 3 (Score 108)
02:05 Answer 4 (Score 48)
02:27 Thank you
--
Full question
https://stackoverflow.com/questions/2083...
Answer 2 links:
[github.com/jd/tenacity]: https://github.com/jd/tenacity
[github.com/litl/backoff]: https://github.com/litl/backoff
[retrying package]: https://pypi.python.org/pypi/retrying
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #loops #exception #tryexcept
#avk47
ACCEPTED ANSWER
Score 562
Do a while True inside your for loop, put your try code inside, and break from that while loop only when your code succeeds.
for i in range(0,100):
while True:
try:
# do stuff
except SomeSpecificException:
continue
break
ANSWER 2
Score 345
I prefer to limit the number of retries, so that if there's a problem with that specific item you will eventually continue onto the next one, thus:
for i in range(100):
for attempt in range(10):
try:
# do thing
except:
# perhaps reconnect, etc.
else:
break
else:
# we failed all the attempts - deal with the consequences.
ANSWER 3
Score 113
UPDATE 2021-12-01:
As of June 2016, the retrying package is no longer being maintained. Consider using the active fork github.com/jd/tenacity, or alternatively github.com/litl/backoff.
The retrying package is a nice way to retry a block of code on failure.
For example:
@retry(wait_random_min=1000, wait_random_max=2000)
def wait_random_1_to_2_s():
print("Randomly wait 1 to 2 seconds between retries")
ANSWER 4
Score 59
Here is a solution similar to others, but it will raise the exception if it doesn't succeed in the prescribed number or retries.
tries = 3
for i in range(tries):
try:
do_the_thing()
except KeyError as e:
if i < tries - 1: # i is zero indexed
continue
else:
raise
break