Python: Merge Multiple PDFs into One
Merge several PDF files into one with Python in a few lines — keep the page order you choose.
A Python decorator that retries a failing API call with exponential backoff — wait longer after each failure, then give up cleanly.
28 lines · Updated Nov 26, 2026
import time
import functools
def retry(tries=3, delay=2, backoff=2, exceptions=(Exception,)):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
wait = delay
for attempt in range(tries):
try:
return func(*args, **kwargs)
except exceptions as error:
if attempt == tries - 1:
raise
print(f"Attempt {attempt + 1} failed: {error}. "
f"Retrying in {wait}s...")
time.sleep(wait)
wait *= backoff
return wrapper
return decorator
@retry(tries=3, delay=2)
def fetch_data(url):
response = requests.get(url, timeout=10)
response.raise_for_status()
return response.json()
External APIs fail more often than you expect: rate limits, timeouts, a server restarting for two seconds. A script that gives up on the first error breaks for no good reason; a script that retries immediately in a tight loop makes things worse. This snippet is a reusable Python decorator that retries a function with exponential backoff — waiting a little longer after each failure — so temporary problems fix themselves.
@retry(...) above def fetch_prices():.Retry-After header, respect it.Is there a library for this? Yes — tenacity is popular. This snippet is useful when you want zero dependencies and to understand the logic.
Related: Telegram bot message · 10 Python automation projects
Save the decorator in a helpers module and import it wherever you call an API. Pass tries, delay and exceptions to suit the API — retry only on transient errors like timeouts, not on 400 errors.
Share this snippet
Merge several PDF files into one with Python in a few lines — keep the page order you choose.
Read the text out of any PDF with Python — the first step for search, summaries and automation.
Send yourself a Telegram message from Python — free alerts for scripts, servers and price trackers.