Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

27 matches
Functions & basics easy

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.

decorator retry error-handling
Python
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:
                …
12 0 Open
Errors & debugging easy

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.

retry connection-error error-handling
Python
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…
15 0 Open
Files & data easy

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.

file-io retry error-handling
Python
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…
14 0 Open
AI & LLM integration patterns medium

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.

llm retry rate-limit
Python
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…
16 0 Open
Automation & scripting medium

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.

web scraping requests beautifulsoup
Python
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()…
99 0 Open
Data pipelines & processing easy

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.

counter metrics data-pipeline
Python
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…
15 0 Open
Data pipelines & processing medium

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.

retry backoff exception-handling
Python
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()
    …
16 0 Open
Cloud + Python medium

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.

retry backoff jitter
Python
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…
18 0 Open
Cloud + Python easy

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.

retry backoff 429
Python
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 …
12 0 Open
System design patterns medium

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.

retry backoff jitter
Python
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…
14 0 Open
System design patterns easy

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.

retry ambassador-pattern mock
Python
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):
     …
15 0 Open
API design & gRPC medium

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.

retry-after api rate-limiting
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 …
14 0 Open
Streaming & messaging easy

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.

dead-letter-queue messaging retry
Python
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…
16 0 Open
Streaming & messaging medium

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.

messaging queue retry
Python
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…
13 0 Open
Streaming & messaging medium

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.

queue retry visibility-timeout
Python
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 …
13 0 Open
Reliability & rate limiting easy

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.

rate-limiting token-bucket retry
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 …
15 0 Open
Reliability & rate limiting medium

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.

retry decorator resilience
Python
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…
13 0 Open
Reliability & rate limiting medium

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.

circuit-breaker resilience fault-tolerance
Python
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 ==…
15 0 Open
Reliability & rate limiting easy

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.

dead-letter-queue queue retry
Python
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,
           …
13 0 Open
Reliability & rate limiting easy

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.

rate-limiting penalty-box lockout
Python
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…
14 0 Open
Reliability & rate limiting easy

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.

retry decorator exceptions
Python
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)
          …
15 0 Open
Reliability & rate limiting medium

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.

outbox retry messaging
Python
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"…
14 0 Open
Reliability & rate limiting easy

How to implement rate limiting in Python

A beginner-friendly Python rate limiter that throttles API calls and retries parsing tasks with exponential backoff.

rate-limiting retry parsing
Python
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…
15 0 Open
Reliability & rate limiting medium

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.

retry backoff mock
Python
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_…
14 0 Open

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

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. 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.