Intermediate
Retry with exponential backoff
Write a function retry(fn, attempts=4, base=1.0, sleep=time.sleep).
It calls fn() and returns what fn() returns. If fn() raises an exception and tries are left, it waits by calling sleep(base * 2 ** n), where n is 0 after the first failure, 1 after the second, and so on. Then it tries again.
If the last try also fails, let that exception go on up (do not catch it). Do not call sleep after the last try.
What Check tests
- returns the result when the first call works
- retries and sleeps 1, 2 after two failures
- re-raises after the last attempt without a final sleep
- attempts=1 never sleeps and re-raises at once
- uses the base value
Stuck? One hint at a time
The solution unlocks after your first Check. Try first: that is where the learning happens.
main.py
Sign in to run your code.
Output
Press Run to see what your program prints.