Retry with backoff in Python
Exponential backoff is the polite way to retry flaky calls.
import time
def retry(fn, attempts=3, delay=0.5):
for attempt in range(attempts):
try:
return fn()
except Exception:
if attempt == attempts - 1:
raise
time.sleep(delay * (2 ** attempt))
How it works
- Calls the function and returns on success.
- On failure,
time.sleepwaits, doubling the delay each attempt. - The final failure re-raises the original exception.
Keywords and builtins used here
defexceptforifraiserangeretryreturntry
The run, in numbers
- Lines
- 10
- Characters to type
- 186
- Tokens
- 54
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 31 seconds.
Step 5 of 5 in Decorators & closures, step 9 of 53 in Pythonic Python.