Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
Create a retry decorator with max attempts in Python
A decorator that retries a function up to a specified number of times when it raises an exception, with an optional delay between attempts.
import functools
import time
def retry(max_attempts, delay=0.1):
"""Retry a function up to max_attempts times on exception."""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(1, max_attempts + 1):
try:
…
Retry an Operation on ConnectionError in Python
Retries an unreliable operation a fixed number of times when it raises a transient ConnectionError, with a small delay between attempts.
import time
import random
def unreliable_operation():
"""Simulates an operation that throws ConnectionError occasionally."""
if random.random() < 0.6:
raise ConnectionError("Transient network failure")
return "Operation succeeded"
def retry_operation(attempts=4, delay=0.2):
"""Retries the o…
How to Read a File with Retry on Temporary IOError in Python
Read a file with automatic retries on temporary IOError/OSError failures, using the pathlib module with configurable attempts and delay.
import time
from pathlib import Path
def read_file_with_retry(filepath: str | Path, max_attempts: int = 3, delay: float = 0.5) -> str:
"""Read a file with retries on temporary IO errors."""
path = Path(filepath)
last_error = None
for attempt in range(max_attempts):
try:
return pat…
How to Retry LLM Calls on Rate Limit Errors in Python
Implement a retry mechanism with exponential backoff for LLM API calls that raises a custom RateLimitError, using a mock function to demonstrate the pattern.
import time
import random
def mock_llm_call():
"""Simulates an LLM API call that may raise a rate limit error."""
if random.random() < 0.4: # 40% chance of rate limit
raise RateLimitError("Rate limit exceeded. Try again later.")
return {"response": "Hello world from mock LLM"}
class RateLimitE…
Build a Complete Web Scraper with Requests and BeautifulSoup in Python
Scrape multiple paginated pages from a website using Requests and BeautifulSoup, with retry logic, error handling, and CSV export.
import requests
from bs4 import BeautifulSoup
import csv
import time
from typing import List, Dict, Optional
class WebScraper:
def __init__(self, base_url: str, output_file: str = "scraped_data.csv"):
self.base_url = base_url
self.output_file = output_file
self.session = requests.Session()…
Count Records Processed per Category in Python
Use a Counter dictionary to track how many records of each type (ok, error, retry) were processed in a data pipeline.
from collections import Counter
import random
processed_counter = Counter()
def process_records(records):
for record in records:
processed_counter[record] += 1
return len(records)
if __name__ == "__main__":
sample_records = [random.choice(["ok", "error", "retry"]) for _ in range(10)]
print(f…
Python Exponential Backoff Retry Example
Retry a flaky function with exponential backoff and jitter-free delays, printing each attempt and finally returning the successful result.
import random
import time
def flaky_function():
if random.random() < 0.6:
raise ConnectionError("Temporary network error")
return "success"
def retry_with_exponential_backoff(func, max_retries=5, base_delay=1.0):
for attempt in range(max_retries + 1):
try:
return func()
…
Exponential Backoff with Jitter for Cloud API Calls in Python
A Python snippet demonstrating exponential backoff with jitter for retrying transient cloud API failures, using a simulated client that has a configurable success rate.
import random
import time
def exponential_backoff_with_jitter(retries=5, base_delay=0.5, max_delay=4.0, jitter_factor=0.3):
for attempt in range(1, retries + 1):
delay = min(max_delay, base_delay * (2 ** (attempt - 1)))
jitter = delay * random.uniform(-jitter_factor, jitter_factor)
effect…
How to Implement Retry with Exponential Backoff for Cloud API 429 Errors in Python
Implement a retry-with-backoff loop in Python to handle 429 throttling errors from cloud APIs, using exponential delay between attempts.
import time
import random
import requests
def api_call(attempt):
"""Mock cloud API that returns 429 for the first two attempts."""
if attempt < 2:
return 429, "Too Many Requests"
return 200, {"data": "success"}
def retry_with_backoff(api_func, max_retries=3, base_delay=0.1):
for attempt in …
How to Implement Retry with Exponential Backoff and Jitter in Python
This code demonstrates a retry mechanism with exponential backoff and optional full jitter, using a flaky mock network call for testing.
import random
import time
def retry_with_backoff(func, max_attempts=5, base_delay=0.1, jitter=True):
"""
Retry a function with exponential backoff and optional full jitter.
"""
for attempt in range(max_attempts):
try:
return func()
except Exception as e:
if att…
How to Mock the Ambassador Pattern Retry Client in Python
This code demonstrates the ambassador pattern for API clients by simulating a flaky request and retrying with exponential backoff, useful for testing resilience in system design.
import time
import random
class RetryingClient:
"""Retry wrapper simulating a flaky ambassador-style API client."""
def __init__(self, max_attempts=3, base_delay=0.1):
self.max_attempts = max_attempts
self.base_delay = base_delay
self.attempts = 0
def _flaky_request(self):
…
How to Handle Retry-After Header in Python
Parse the Retry-After header from rate-limited API responses and implement retry logic with proper delays in Python.
```python
import time
from datetime import datetime, timedelta
class RetryAfterHandler:
def __init__(self, max_retries=3):
self.max_retries = max_retries
def get_retry_after_seconds(self, response_headers):
retry_after_value = response_headers.get("Retry-After")
if retry_after_value …
Dead Letter Queue Failed Messages List Mock in Python
Implements a simple in-memory dead letter queue to collect, list, and retry failed messages, with JSON serialization for inspection in streaming pipelines.
import json
from collections import deque
class Message:
def __init__(self, message_id, payload, attempts=0):
self.message_id = message_id
self.payload = payload
self.attempts = attempts
def __repr__(self):
return f"Message(id={self.message_id}, attempts={self.attempts})"
c…
How to Implement At-Least-Once Delivery with Acknowledgment in Python
This code demonstrates a mock message broker with at-least-once delivery, including retry logic and acknowledgment after successful processing.
import time
import uuid
from collections import deque
class MockMessageBroker:
def __init__(self):
self.queue = deque()
self.acked = set()
def publish(self, payload: str) -> str:
msg_id = str(uuid.uuid4())
self.queue.append((msg_id, payload))
return msg_id
def po…
Implement a retry queue with visibility timeout in Python
This code simulates a message queue with a visibility timeout, allowing messages to be retried if not deleted before the timeout expires.
import time
from collections import deque
class SimpleQueue:
def __init__(self, visibility_timeout=2):
self.queue = deque()
self.in_flight = {}
self.visibility_timeout = visibility_timeout
def send(self, message):
self.queue.append(message)
def receive(self):
if …
How to Build a Rate Limiter in Python
A beginner-friendly token bucket rate limiter with retry logic for handling API rate limits in Python.
import time
import random
class RateLimiter:
"""Simple token bucket rate limiter for beginners."""
def __init__(self, max_tokens=5, refill_rate=1.0):
self.max_tokens = max_tokens
self.tokens = max_tokens
self.refill_rate = refill_rate # tokens per second
self.last_refill …
How to Cap Retry Attempts in Python with a Decorator
Build a reusable retry decorator that caps attempts, adds delays, and lets flaky services fail fast instead of hanging.
import random
from functools import wraps
from time import sleep
def retry(max_attempts, delay=0.1):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
attempts = 0
while attempts < max_attempts:
try:
return func(*args, **kw…
How to Implement a Circuit Breaker in Python
A Python dataclass that provides circuit breaker logic with closed, open, and half-open states to fail fast on repeated errors.
from dataclasses import dataclass
from datetime import datetime, timedelta
import time
@dataclass
class CircuitBreaker:
failure_threshold: int = 3
timeout_seconds: float = 5.0
failures: int = 0
state: str = "closed"
last_failure: datetime = None
def call(self, func):
if self.state ==…
How to Implement a Dead Letter Queue Replay in Python
A mock Dead Letter Queue that stores failed messages with retry attempts and replays them with a simple retry counter.
import json
from collections import deque
class DeadLetterQueue:
def __init__(self):
self.messages = deque()
def add_message(self, message_id, payload, attempts=3):
"""Add a message to the DLQ with retry metadata."""
self.messages.append({
"id": message_id,
…
How to Implement a Temporary Block in Python
Build a reusable PenaltyBox class that temporarily blocks access after a failure and reports remaining lockout time.
class PenaltyBox:
def __init__(self, block_seconds: int = 30):
self.block_seconds = block_seconds
self._blocked_until = 0.0
self._attempts = 0
def try_access(self, current_time: float) -> bool:
if self._blocked_until and current_time < self._blocked_until:
return Fa…
How to Retry on Specific Exception Tuples in Python
A decorator-based retry pattern that retries a function only when it raises exceptions specified in a tuple, with configurable retries and delay.
import time
import random
from unittest.mock import patch
def retry_on_exceptions(retries=3, exceptions=(ValueError,), delay=0.1):
def decorator(func):
def wrapper(*args, **kwargs):
for attempt in range(retries):
try:
return func(*args, **kwargs)
…
How to Simulate an Outbox Pattern with Reliable Retry in Python
This code implements a mock outbox pattern with records, delivery attempts, and retries to simulate reliable message publishing.
import time
import itertools
class Outbox:
def __init__(self):
self._records = []
self._seq = itertools.count(1)
def publish(self, topic, payload):
record = {
"id": next(self._seq),
"topic": topic,
"payload": payload,
"status": "pending"…
How to implement rate limiting in Python
A beginner-friendly Python rate limiter that throttles API calls and retries parsing tasks with exponential backoff.
import time
import random
class RateLimiter:
def __init__(self, max_calls, per_seconds):
self.max_calls = max_calls
self.per_seconds = per_seconds
self.timestamps = []
def allow(self):
now = time.time()
self.timestamps = [t for t in self.timestamps if now - t < sel…
How to retry idempotent operations with a mock in Python
Wrap a flaky idempotent operation in a retry loop with exponential backoff, and use unittest.mock to deterministically test the str's behavior.
import random
import time
from unittest.mock import Mock
def idempotent_operation(value):
"""Simulate an idempotent operation that sometimes fails."""
if random.random() < 0.6: # 60% failure rate
raise ConnectionError("Temporary failure")
return value * 2
def retry_with_backoff(operation, max_…
Browse by section
Each section groups closely related Python snippets.
Guide: free Python code samples library
Copy-ready Python snippets for learners and developers
PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.
How to use this library
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- Run it in the IDE, tweak values, then take a related quiz or tutorial lesson
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.