runtime
180 / 500
question 180 Exceptions & Validation · hard

Retry a flaky call, but only when it's worth it

A price service sometimes times out and works on the next try; other failures (a bad request) will fail every time. Write a helper that retries only the temporary kind. Define TemporaryFailure, then with_retries(action, attempts).

Error typeTemporaryFailure, a kind of Exception
Functionwith_retries(action, attempts): call action() (no arguments) up to attempts times
Returnsthe result of the first call that succeeds
Retriesonly after TemporaryFailure; when every attempt raises it, raise the last one again
Other errorsescape at once, without another attempt
Bad inputattempts below 1 raises ValueError("attempts must be at least 1") without calling action

Loading your progress…

Retry a flaky call, but only when it's worth it — Python practice · Runtime