Write retry(func, attempts) that calls func until it succeeds, catching ConnectionError, and re-raises the last error after the final attempt. Test it with a simulated flaky connection.
def retry(func, attempts=3):
for n in range(1, attempts + 1):
try:
return func()
except ConnectionError as e:
print(f"attempt {n} failed: {e}")
if n == attempts:
raise
def flaky(fail_times):
calls = {"n": 0}
def connect():
calls["n"] += 1
if calls["n"] <= fail_times:
raise ConnectionError("server busy")
return "connected"
return connect
print(retry(flaky(2)))
try:
retry(flaky(5))
except ConnectionError:
print("giving up")
Output Verified by running it on Python 3
attempt 1 failed: server busy
attempt 2 failed: server busy
connected
attempt 1 failed: server busy
attempt 2 failed: server busy
attempt 3 failed: server busy
giving up
Returning inside try ends the loop on success; the bare raise on the last attempt passes the error to the caller.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!