Is there a more concise way to perform this in Python:
tries = 10
for x in range(tries):
try:
foo()
break
except Exception as e:
if x == tries-1:
raise e
The point of it is that sometimes the operation fails (for whatever reason), but we want to allow for a number of retries before raising an exception.
A usual way to make something more concise is to factor it out.
def retrying(max_attempts, func, *args, **kwargs):
attempts_left = max_attempts
while attempts_left: # could be 'while True', but an extra check won't hurt
try:
return func(*args, **kwargs)
except SomeException:
attempts_left -= 1
if not attempts_left:
raise
The above code only catches SomeException
and not Exception
, else it would keep retrying when you have an undefined identifier in your code. Usually catching all exceptions is a bad idea, unless you re-raise them immediately. The lone raise
preserves the func
's stack trace. You could pass the list of exceptions to catch as a parameter.
The code above does most sense if you have several places where you need to retry actions. Then you just write retrying(3, foo, 1, b=2)
instead of foo(1, b=2)
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments