Command Palette

Search for a command to run...

Hectal
Phase 15: Python for APIs, Services and Tools
Python · Exercise 2 of 6 PreviousNext
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

  1. returns the result when the first call works
  2. retries and sleeps 1, 2 after two failures
  3. re-raises after the last attempt without a final sleep
  4. attempts=1 never sleeps and re-raises at once
  5. 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.