Reference library

Python Code Samples

Easy snippets you can copy, study, and run in the browser editor.

53 matches
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
OOP & classes easy

How to define a custom exception class in Python with an error code attribute

Create a custom exception class with extra attributes like an error code, then raise and catch it in a try/except block.

exceptions classes error-handling
Python
class UserNotFoundError(Exception):
    def __init__(self, user_id, error_code=404):
        self.user_id = user_id
        self.error_code = error_code
        super().__init__(f"User with ID {user_id} was not found (error code: {error_code})")

def find_user(user_id, users_db):
    if user_id not in users_db:
      …
15 0 Open
Algorithms & data structures easy

Find k Closest Points to Origin in Python

Sorts a list of (x, y) point tuples by their Euclidean distance from the origin and returns the k nearest points.

sorting euclidean-distance geometry
Python
import math

def k_closest(points, k):
    points.sort(key=lambda p: math.sqrt(p[0]**2 + p[1]**2))
    return points[:k]

if __name__ == "__main__":
    points = [(1, 2), (3, 4), (-1, 0), (5, 5), (0, 1)]
    k = 3
    result = k_closest(points, k)
    print(f"Original points: {points}")
    print(f"K closest points (k…
13 0 Open
Automation & scripting easy

How to generate an htpasswd bcrypt entry in Python

Create a mock htpasswd file entry with a bcrypt-hashed password for a given username using a simple Python script.

bcrypt htpasswd password
Python
import bcrypt

def mock_htpasswd_entry(username, password):
    salt = bcrypt.gensalt(rounds=12)
    hashed = bcrypt.hashpw(password.encode(), salt).decode()
    return f"{username}:{hashed}"

if __name__ == "__main__":
    entry = mock_htpasswd_entry("demo_user", "s3cretP@ss")
    print(entry)
15 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
Cloud + Python easy

How to Generate a Mock EKS Kubeconfig in Python

Generate a minimal kubeconfig dict with a mock EKS cluster entry and dump it to YAML using PyYAML.

kubeconfig eks yaml
Python
import yaml
from pathlib import Path


def mock_eks_kubeconfig(cluster_name: str) -> dict:
    """Return a minimal kubeconfig dict with a mock EKS cluster entry."""
    return {
        "apiVersion": "v1",
        "kind": "Config",
        "clusters": [
            {
                "name": f"arn:aws:eks:us-east-1:123…
15 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
Modern tooling easy

How to Initialize Sentry SDK with a Mock DSN in Python

Initialize the Sentry SDK in Python with a mock DSN to test error tracking without sending real events, then verify the DSN configuration.

sentry sdk dsn
Python
import sentry_sdk

# Initialize Sentry SDK with a mock DSN (no real events will be sent)
sentry_sdk.init(
    dsn="https://mock-public@mock-host/mock-project",
    traces_sample_rate=1.0,
    environment="development",
)

# Capture a test message to confirm SDK is configured
sentry_sdk.capture_message("Test message fr…
13 0 Open
Modern tooling easy

How to Mock OpenTelemetry Tracer Setup in Python

Set up a mock OpenTelemetry tracer with an in-memory span exporter to capture spans for testing and debugging.

opentelemetry testing tracing
Python
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter


def setup_tracer():
    provider = TracerProvider()
    exporter = InMemorySpanExpo…
13 0 Open
Modern tooling easy

How to Mock Poetry pyproject.toml Dependencies Sections in Python

Parse and extract dependency lists from Poetry-style pyproject.toml text using Python's standard library.

pyproject poetry toml
Python
from pathlib import Path
import re


def parse_pyproject_dependencies(text):
    """Extract dependencies from a pyproject.toml style text."""
    lines = text.splitlines()
    sections = {
        "dependencies": [],
        "dev": [],
        "optional": [],
    }
    current_section = None

    patterns = {
        …
15 0 Open
Concurrency & performance easy

How to Run an Async Main with asyncio.run in Python

Show the canonical entry point for an asyncio program: define an async main, then launch it with asyncio.run.

asyncio event loop entry point
Python
import asyncio


async def main():
    print("Hello from async main")
    await asyncio.sleep(0.1)
    print("Done")


if __name__ == "__main__":
    asyncio.run(main())
16 0 Open
System design patterns easy

How to Build a Simple Service Discovery Registry in Python

A lightweight in-memory service registry class using a dict — register, deregister, and discover services with host, port, and version.

service-discovery registry dict
Python
class ServiceRegistry:
    def __init__(self):
        self._services = {}

    def register(self, name, host, port, version="1.0"):
        self._services[name] = {
            "host": host,
            "port": port,
            "version": version
        }

    def deregister(self, name):
        return self._servic…
13 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
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
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 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 Mock a Try Confirm Cancel Pattern in Python

Define a simple class with confirm and cancel methods, execute a try confirm with error handling, and print the final state.

try-except mock class
Python
class TCC:
    def __init__(self):
        self.confirmed = False
        self.cancelled = False

    def confirm(self):
        self.confirmed = True
        return "confirmed"

    def cancel(self):
        self.cancelled = True
        return "cancelled"

    def try_confirm(self):
        try:
            result =…
13 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 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
Observability & SRE easy

How to Do Structured JSON Logging in Python

Create a custom logging formatter that outputs each log entry as a single JSON line with timestamp, level, logger name, and message.

logging json observability
Python
import json
import logging
from datetime import datetime


class JsonFormatter(logging.Formatter):
    def format(self, record):
        log_entry = {
            "timestamp": datetime.utcnow().isoformat() + "Z",
            "level": record.levelname,
            "logger": record.name,
            "message": record.ge…
14 0 Open
Microservices patterns easy

How to Build a Health Check Service Registry in Python

Build a minimal Python service registry that handles registration, deregistration, health checks, and service listing in one simple class.

microservices health-check service-discovery
Python
import random
import time


class ServiceRegistry:
    def __init__(self):
        self.services = {}

    def register(self, name, address):
        self.services[name] = {
            "address": address,
            "status": "healthy",
            "registered_at": time.time(),
            "checks": 0
        }
    …
13 0 Open
Microservices patterns easy

How to Build an In-Memory Service Registry Mock in Python

A simple in-memory ServiceRegistry class to register, retrieve, list, and unregister microservice endpoints or configs using a dict, with KeyError guards.

service-registry microservices in-memory
Python
class ServiceRegistry:
    def __init__(self):
        self._services = {}

    def register(self, name, service):
        self._services[name] = service

    def unregister(self, name):
        if name not in self._services:
            raise KeyError(f"Service '{name}' not found")
        del self._services[name]

 …
14 0 Open
Microservices patterns easy

How to Mock a Schema Registry Avro Record in Python

Encode a Python dict into Avro binary using an inline schema, mimicking a schema registry record for tests or mocks.

avro schema-registry serialization
Python
import io
from avro.schema import parse
from avro.io import DatumWriter, BinaryEncoder

schema_json = """
{
  "type": "record",
  "name": "User",
  "fields": [
    {"name": "name", "type": "string"},
    {"name": "age", "type": "int"},
    {"name": "email", "type": ["null", "string"], "default": null}
  ]
}
"""

schem…
15 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.