Example — Snippet Content Type
Example title: Python Retry With Backoff
Guidance: Use snippet for one ready-to-run code block that solves a single task. Include imports, keep context minimal, and avoid framework setup or unrelated boilerplate.
Example content
A Python retry-with-backoff snippet for retrying a failing call a few times with increasing delays. Copy it into a module and pass the callable you want to retry.
Snippet
import time
import random
def retry(fn, attempts=3, base_delay=0.5):
for i in range(attempts):
try:
return fn()
except Exception:
if i == attempts - 1:
raise
time.sleep(base_delay * (2 ** i) + random.uniform(0, 0.25))
Usage
result = retry(lambda: call_api())
Notes
- No framework setup, no boilerplate.
- One task per snippet.
- Include imports so it runs as-is.