Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
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.
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, …
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.
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 …
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.
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,
…
How to Build a Docker Image Tag Script in Python
Generate consistent Docker image tags from service names and versions with automatic normalization.
#!/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__ == "…
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.
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 …
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.
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…
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.
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…
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.
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_…
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.
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…
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.
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…
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.
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…
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.
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…
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.
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"[…
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.
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(…
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.
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(…
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.
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):
…
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.
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…
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.
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…
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.
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]:
…
Implement Bulkhead Thread Pool Isolation in Python
Create isolated thread pools with a bulkhead pattern to protect different services from cascading failures.
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 = …
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.
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…
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.
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…
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.
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."""
…
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.
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,
…
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.