Reference library

Python Code Samples

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

99 matches
AI & LLM integration patterns medium

Circuit Breaker Pattern in Python for LLM API Calls

Implements a circuit breaker class that wraps LLM client calls to fail fast when the service is degrading, then recover automatically after a timeout.

circuit-breaker llm resilience
Python
import time

class CircuitBreaker:
    def __init__(self, failure_threshold=3, recovery_timeout=5):
        self.failure_threshold = failure_threshold
        self.recovery_timeout = recovery_timeout
        self.failure_count = 0
        self.state = "closed"
        self.last_failure_time = None

    def call(self, …
14 0 Open
Automation & scripting medium

Build a Complete Website Sitemap Generator Without External Services

Crawl a website recursively using only Python's standard library to generate a structured sitemap of internal links.

sitemap web-crawler html-parser
Python
import json
from urllib.parse import urlparse, urljoin
from collections import deque
import urllib.request
import urllib.error
import re
from html.parser import HTMLParser

class SitemapParser(HTMLParser):
    def __init__(self, base_url):
        super().__init__()
        self.base_url = base_url
        self.links …
44 0 Open
Automation & scripting easy

Check Service Ping Status and Exit Code in Python

Ping a list of hosts, print OK/FAIL per host, and exit with a non-zero code when any host is unreachable.

subprocess ping exit-code
Python
import subprocess
import sys

SERVICES = [
    "8.8.8.8",
    "1.1.1.1",
    "invalid-host",
]

def main():
    failed = []
    for host in SERVICES:
        result = subprocess.run(
            ["ping", "-c", "1", "-W", "2", host],
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
        …
16 0 Open
Automation & scripting easy

How to Build a Docker Image Tag Script in Python

Generate consistent Docker image tags from service names and versions with automatic normalization.

docker scripting cli
Python
#!/usr/bin/env python3
"""Mock script for building docker image tags."""


def build_tag(service_name: str, version: str, registry: str = "docker.io") -> str:
    """Construct a docker image tag."""
    safe_name = service_name.lower().replace("_", "-")
    return f"{registry}/{safe_name}:{version}"


if __name__ == "…
12 0 Open
Automation & scripting easy

Mock systemctl Wrapper in Python for Service Testing

A Python class-based mock of systemctl that simulates start, stop, restart, and status operations for a service, useful for testing automation scripts.

systemctl mock automation
Python
import subprocess
import sys

class ServiceManager:
    def __init__(self, service_name):
        self.service_name = service_name
        self.status = "inactive"
    
    def start(self):
        self.status = "active"
        print(f"Starting {self.service_name}... OK")
    
    def stop(self):
        self.status …
14 0 Open
Cloud + Python easy

Generate an Idempotency-Key header mock with UUID in Python

This code provides a mock idempotency service that generates a UUID-based Idempotency-Key header token and validates it, useful for simulating production API behavior in tests.

uuid idempotency mock
Python
import uuid

class MockIdempotencyService:
    def __init__(self):
        self._tokens = {}

    def get_token(self, header_name="Idempotency-Key"):
        token = str(uuid.uuid4())
        self._tokens[header_name] = token
        return token

    def validate(self, header_name="Idempotency-Key"):
        return s…
11 0 Open
Cloud + Python easy

How to Calculate Cloud Cost Estimates with a Python Dictionary

Mocks a cloud pricing calculator using a dictionary of service rates and computes total estimated cost for given service hours.

cost-estimate dictionary mock
Python
def estimate_cost(service, hours, rate_table=None):
    if rate_table is None:
        rate_table = {
            "basic": 50,
            "standard": 75,
            "premium": 100
        }
    if service not in rate_table:
        raise ValueError(f"Unknown service: {service}")
    return rate_table[service] * hour…
13 0 Open
Cloud + Python medium

How to Mock Azure Key Vault Secret Get in Python

Mock an Azure Key Vault client's get_secret method with unittest.mock to test functions that retrieve secret values without hitting the real service.

azure key-vault unittest
Python
import unittest
from unittest.mock import MagicMock, patch


def get_secret(key_vault_client, secret_name):
    """Retrieve a secret value from an Azure Key Vault client."""
    secret = key_vault_client.get_secret(secret_name)
    return secret.value


class TestKeyVaultSecretGet(unittest.TestCase):
    def test_get_…
13 0 Open
Cloud + Python easy

How to Mock Azure Service Bus Queue in Python

A lightweight in-memory mock of the Azure Service Bus queue API for local testing without cloud dependencies.

azure service-bus mock
Python
import json
import time
from collections import deque

class ServiceBusQueueMock:
    def __init__(self, queue_name):
        self.queue_name = queue_name
        self._messages = deque()
        self._dead_letter_queue = deque()
        self._message_counter = 0

    def send_message(self, body, message_id=None, prop…
14 0 Open
Cloud + Python medium

How to Mock RDS Snapshot Create and Restore in Python

Mock AWS RDS snapshot creation and restore operations in Python tests using moto and boto3 without hitting real AWS services.

boto3 moto rds
Python
import boto3
from moto import mock_rds


@mock_rds
def create_and_restore_snapshot():
    client = boto3.client("rds", region_name="us-east-1")
    client.create_db_instance(
        DBInstanceIdentifier="my-db",
        DBInstanceClass="db.t3.micro",
        Engine="postgres",
        AllocatedStorage=20,
        Mas…
14 0 Open
Cloud + Python easy

How to Parse Cloud JSON Data in Python

A helper function that safely parses JSON payloads from cloud services into a clean dict with defaults and error handling.

json cloud parsing
Python
import json
from typing import Dict, Any

def parse_cloud_data(payload: str) -> Dict[str, Any]:
    """Parse a JSON payload from a cloud service into a clean dict."""
    try:
        data = json.loads(payload)
        return {
            "status": data.get("status", "unknown"),
            "region": data.get("region…
15 0 Open
Cloud + Python easy

How to plan reserved capacity from a CSV in Python

Read a CSV of workloads with csv.DictReader and compute a mock reserved capacity plan with headroom per service.

csv capacity-planning cloud
Python
import csv
import io


def plan_reserved_capacity(workloads_csv: str) -> list[dict]:
    """Read a CSV of workloads and return a plan for reserved capacity per service."""
    reader = csv.DictReader(io.StringIO(workloads_csv))
    plan = []
    for row in reader:
        service = row["service"]
        avg_load = fl…
11 0 Open
Modern tooling easy

How to Mock docker compose up Healthcheck in Python

Simulate docker compose up with a healthcheck cycle using Python loops, delays, and simulated service statuses.

docker healthcheck simulation
Python
import subprocess
import time

def run_healthcheck():
    """Mock a docker compose up with a healthcheck cycle."""
    services = ["web", "db", "cache"]
    
    print("Starting docker compose services...")
    for service in services:
        print(f"[{service}] starting...")
        time.sleep(0.1)
        print(f"[…
15 0 Open
Testing & modern typing easy

Dependency Injection in Python for Testability

Inject a config dependency into a service so you can swap a real environment-based config for a fake one in tests.

dependency-injection testing mocking
Python
import os


class Config:
    """Simple config loader that can be easily faked in tests."""
    def get(self, key, default=None):
        return os.environ.get(key, default)


class UserService:
    def __init__(self, config):
        self.config = config

    def get_timeout(self):
        return int(self.config.get(…
16 0 Open
Testing & modern typing medium

How to Run an Integration Test with Docker Compose Mock in Python

Run a Python integration test against a docker-compose environment, using mocks to simulate service health and business logic responses.

docker integration-testing mocking
Python
import subprocess
import json
from typing import Dict

def run_integration_test() -> Dict[str, str]:
    """
    Simulates an integration test against a docker-compose environment
    using a mock service that returns canned responses.
    """
    # Mock docker-compose environment check
    env_ready = subprocess.run(…
15 0 Open
System design patterns medium

Circuit Breaker Pattern in Python: Closed, Open, and Half-Open States

Implement a circuit breaker with closed, open, and half-open states to prevent repeated calls to failing services and allow recovery after a timeout.

circuit-breaker resilience fault-tolerance
Python
class CircuitBreaker:
    def __init__(self, failure_threshold=3, timeout_seconds=5):
        self.failure_threshold = failure_threshold
        self.timeout_seconds = timeout_seconds
        self.state = "closed"
        self.failure_count = 0
        self.last_failure_time = None

    def record_success(self):
     …
14 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 medium

How to implement saga orchestration with compensating steps in Python

Orchestrate a distributed transaction across services, rolling back completed steps with compensations when a later step fails.

saga distributed-transactions compensation
Python
class InventoryService:
    def reserve(self, order_id):
        print(f"[Inventory] Reserving stock for order {order_id}")
        return True

    def compensate(self, order_id):
        print(f"[Inventory] Releasing stock for order {order_id}")


class PaymentService:
    def charge(self, order_id):
        print(f…
14 0 Open
System design patterns easy

How to mock the domain center in an onion architecture in Python

Define a repository interface and an in-memory mock to test domain services without touching infrastructure.

onion-architecture repository-pattern dependency-injection
Python
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Dict, List, Optional


@dataclass
class Order:
    id: int
    customer: str
    items: List[str]
    total: float


class OrderRepository(ABC):
    @abstractmethod
    def find_by_id(self, order_id: int) -> Optional[Order]:
     …
11 0 Open
System design patterns medium

Implement Bulkhead Thread Pool Isolation in Python

Create isolated thread pools with a bulkhead pattern to protect different services from cascading failures.

bulkhead threadpool concurrency
Python
import threading
import time
import random
from concurrent.futures import ThreadPoolExecutor


class Bulkhead:
    """Simple bulkhead isolation: separate thread pools for different tasks."""

    def __init__(self, max_workers):
        self.executor = ThreadPoolExecutor(max_workers=max_workers)
        self.active = …
13 0 Open
System design patterns medium

Lazy loading with a proxy in Python: defer expensive service creation

A lazy proxy defers creating an expensive service object until its method is first called, then caches it for reuse.

proxy lazy-loading design-patterns
Python
import time
import random


class ExpensiveService:
    def __init__(self, name):
        self.name = name
        print(f"Creating expensive service: {self.name}")

    def fetch_data(self):
        time.sleep(1)
        return f"Data from {self.name}: {random.randint(1, 100)}"


class LazyProxy:
    def __init__(sel…
15 0 Open
API design & gRPC easy

How to Build a Simple Filter Helper in Python for API Design

Create a reusable data filter service with dataclasses that mimics gRPC request/response patterns for filtering dataset records.

filtering dataclasses grpc
Python
from dataclasses import dataclass, field
from typing import List, Optional, Dict, Any


@dataclass
class FilterRequest:
    """A simple filter request mirroring a gRPC message structure."""
    field_name: str
    operator: str  # eq, ne, gt, lt, contains
    value: Any
    page_size: int = 10
    page_token: Optional…
13 0 Open
API design & gRPC easy

How to Build a Simple gRPC-Style Data Service in Python

Create a beginner-friendly gRPC-style service with dataclasses to simulate GetUser and CreateUser RPCs.

grpc dataclasses api-design
Python
from dataclasses import dataclass
from typing import Optional


@dataclass
class User:
    id: int
    name: str
    email: str


class UserService:
    """Simple gRPC-style service contract for beginner learners."""

    def get_user(self, user_id: int) -> Optional[User]:
        """Simulated gRPC GetUser RPC."""
   …
13 0 Open
API design & gRPC easy

How to Parse gRPC Request Data in Python

Build a beginner-friendly gRPC service handler that parses incoming protobuf messages into Python dictionaries and starts a simple gRPC server.

grpc protobuf api
Python
from google.protobuf import json_format
import grpc
from concurrent import futures
import time


class DataParsingService:
    def parse(self, request):
        return {
            "received_json": json_format.MessageToJson(request),
            "parsed_fields": {
                "name": request.name,
               …
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.