Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Validate Dataclass Fields with Python Type Hints
A beginner-friendly helper that checks if instance attributes match their declared type hints using dataclasses and get_type_hints.
from typing import Any, TypeVar, get_type_hints
from dataclasses import dataclass
T = TypeVar("T")
@dataclass
class User:
name: str
age: int
email: str
def validate_fields(obj: Any) -> dict[str, bool]:
"""Check if object attributes match declared type hints."""
hints = get_type_hints(obj.__class…
How to Mock a Metrics Decorator in Python with unittest.mock
This code demonstrates a timing decorator that wraps a function to measure execution time and prints the duration, with a unit test using unittest.mock to patch the print function and assert it was called.
import time
from functools import wraps
from unittest.mock import patch
def add_metrics(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
elapsed = time.perf_counter() - start
print(f"{func.__name__} took {elapsed:.6f}s…
Observer Pattern with Mock Metrics in Python
Implement the Observer pattern with a mock metrics collector to track state changes and verify notifications.
import unittest
from unittest.mock import Mock
class Subject:
def __init__(self):
self._state = 0
self._observers = []
def attach(self, observer):
self._observers.append(observer)
def set_state(self, value):
if value != self._state:
self._state = value
…
Route Messages to Handlers with a Python Dict
This code demonstrates a simple message routing pattern using a dictionary to map topic keys to handler functions, with a default handler for unmatched topics.
def route_message(message, routing_table):
"""Route a message to the correct handler based on the topic key."""
topic = message.get("topic", "default")
handler = routing_table.get(topic, routing_table.get("default"))
return handler(message)
def handle_orders(message):
return f"Orders handler proc…
Create a Data Helper in Python for gRPC-style APIs
This code builds a simple DataHelper class that mimics gRPC request/response handling with in-memory storage, JSON serialization, and basic CRUD operations for beginners.
import json
from dataclasses import dataclass, asdict
from typing import Dict, Any
@dataclass
class User:
user_id: int
name: str
email: str
class DataHelper:
"""Simple helper to demonstrate gRPC-like data handling for beginners."""
def __init__(self) -> None:
self._users: Dict[int, Use…
How to Build a Simple Data Helper in Python for API Design
Create a beginner-friendly DataHelper class that demonstrates basic CRUD operations (add, get, list, remove) using an in-memory dictionary, ideal for learning API design concepts.
class DataHelper:
"""Simple data helper for beginners learning API design concepts."""
def __init__(self):
self._data = {}
def add_record(self, key, value):
"""Add a record to the store."""
self._data[key] = value
return f"Added: {key} -> {value}"
def get_…
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 Mock X-RateLimit Headers in Python
This code creates a local HTTP server that mimics rate limit headers (X-RateLimit-Limit, Remaining, Reset, Update) and returns 429 responses when the limit is exceeded.
import time
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
class RateLimitHandler(BaseHTTPRequestHandler):
RATE_LIMIT = 5 # max requests allowed
WINDOW_SECONDS = 60 # per time window
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
…
How to Implement an In-Memory Pub/Sub System in Python
This code implements a simple in-memory publish/subscribe system in Python, allowing topics, callbacks, and message broadcasting.
class PubSub:
def __init__(self):
self.topics = {}
def subscribe(self, topic, callback):
if topic not in self.topics:
self.topics[topic] = []
self.topics[topic].append(callback)
return lambda: self.unsubscribe(topic, callback)
def unsubscribe(self, topic, callb…
How to Stream Join Windowed Mock Topics in Python
Simulates two message topics and joins their events when timestamps fall within a sliding time window using Python generators and deques.
import itertools
import random
import time
from collections import deque
from dataclasses import dataclass, field
@dataclass
class Event:
key: str
value: int
timestamp: float = field(default_factory=time.time)
def generate_topic(prefix, keys, start_time):
while True:
yield Event(
…
In-Memory PubSub Topic Subscribe Mock in Python
Build a thread-safe in-memory publish/subscribe mock where handlers subscribe to named topics and receive every message published to them.
class PubSub:
def __init__(self):
self.topics = {}
def subscribe(self, topic, callback):
if topic not in self.topics:
self.topics[topic] = []
self.topics[topic].append(callback)
def publish(self, topic, message):
for callback in self.topics.get(topic, []):
…
Simulate RabbitMQ QoS Prefetch Count in Python
Mocks RabbitMQ QoS prefetch semantics using threading and a queue to cap concurrent unacked message processing per worker.
import threading
import time
import queue
class RabbitMQMock:
def __init__(self, prefetch_count=1):
self.prefetch_count = prefetch_count
self.channel_queue = queue.Queue()
self.currently_processing = 0
self.lock = threading.Lock()
def start_consuming(self, messages, worker_co…
How to Implement a Redis-Like Cache Dictionary in Python
Build a RedisMockDict class that mimics basic Redis key-value operations with TTL support, expiry cleanup, and standard dict-like methods.
from collections import OrderedDict
import time
class RedisMockDict:
def __init__(self, ttl=None):
self._data = OrderedDict()
self._ttl = ttl # default TTL in seconds, None = no expiry
self._expiry = {}
def set(self, key, value, ttl=None):
"""Set a key-value pair with optiona…
Mock Redis Distributed Lock in Python with SET NX EX
A minimal in-memory mock of Redis SET NX EX distributed lock semantics for testing concurrent code without a real Redis server.
import time
import threading
import uuid
from typing import Optional
class RedisLockMock:
"""A minimal mock of Redis SET NX EX distributed lock semantics."""
def __init__(self):
self._store = {} # key -> (value, expiry_epoch)
def acquire(self, key: str, token: str, ttl_seconds: int) -> bool:
…
Export Metrics with OTLP Mock in Python
Simulates system metric collection and exports them as an OTLP-like JSON payload using only Python's standard library.
from dataclasses import dataclass, asdict
import json
import random
import time
@dataclass
class Metric:
name: str
value: float
timestamp: int
unit: str = "1"
def collect_system_metrics() -> list[Metric]:
"""Mock metric collection for OTLP export simulation."""
now = int(time.time())
re…
Generate Mock CPU and Memory Metrics in Python
Build a mock_host_metrics() generator that outputs realistic CPU and memory usage percentages for monitoring demos and tests.
import time
import random
def mock_host_metrics():
"""Generate mock CPU and memory metrics for a host."""
cpu_percent = round(random.uniform(10.0, 95.0), 1)
memory_percent = round(random.uniform(20.0, 90.0), 1)
memory_used_mb = round(random.uniform(512, 8192), 1)
return {
"timestamp": in…
Generate Prometheus Text Exposition Format in Python
Mock a Prometheus metrics endpoint by formatting metrics into the text exposition format with HELP, TYPE, and sample lines.
import time
from random import randint
# Mock a Prometheus metrics endpoint output
metrics = {
"http_requests_total": {
"help": "Total number of HTTP requests",
"type": "counter",
"samples": [
{"labels": {"method": "get", "code": "200"}, "value": randint(1000, 9999)},
…
Generate Synthetic CPU Utilization Metrics in Python
Creates realistic time-series CPU utilization samples with timestamps, noise, and output as structured JSON for observability demos and testing.
from datetime import datetime, timedelta
import random
import json
def generate_metric_samples(base_value, noise, count=60, interval_minutes=1):
"""Generate realistic CPU utilization samples for a given time window."""
timestamps = []
values = []
now = datetime.utcnow()
start_time = now - timede…
Generate Synthetic SRE Metrics and Calculate Availability in Python
Create realistic service metrics with random latency, error rate, and request counts, then compute availability and summarize the stream for SLO checks.
from datetime import datetime, timedelta
import random
def generate_service_metrics(service_name: str, minutes: int = 30) -> list[dict]:
"""Generate synthetic SRE metrics for a service across recent minutes."""
metrics = []
now = datetime.now()
for i in range(minutes):
timestamp = now - t…
How to Build a Metrics Counter with Increment and Snapshot in Python
A simple dict-backed MetricsCounter class that increments named counters and returns a snapshot of the current values.
class MetricsCounter:
def __init__(self):
self._metrics = {}
def increment(self, key, delta=1):
self._metrics[key] = self._metrics.get(key, 0) + delta
def snapshot(self):
return dict(self._metrics)
if __name__ == "__main__":
counter = MetricsCounter()
counter.increment("…
How to Build a Python Latency Histogram with Mock Buckets
This code implements a mock latency histogram that records request durations into configurable buckets and outputs counts, total, and average latency.
import time
import random
from collections import Counter
class LatencyHistogram:
def __init__(self, buckets):
self.buckets = sorted(buckets)
self.counts = Counter()
self.total = 0
self.sum_latency = 0
def record(self, latency_ms):
for i, boundary in enumerate(self.bu…
How to Build an HTTP Server Request Duration Histogram in Python
Create a small HTTP server that times each GET request, buckets the duration, and prints a histogram on shutdown.
import time
import random
from collections import Counter
from http.server import HTTPServer, BaseHTTPRequestHandler
class HistogramHandler(BaseHTTPRequestHandler):
response_times = Counter()
def do_GET(self):
start = time.perf_counter()
time.sleep(random.uniform(0.001, 0.1))
duratio…
How to Calculate Apdex Score from Latency Data in Python
Generate simulated latency samples and compute the Apdex score to gauge user satisfaction with an application's performance.
import random
import statistics
def generate_latencies(count=100, base=100, stddev=30):
return [max(0, random.gauss(base, stddev)) for _ in range(count)]
def apdex(latencies, threshold=200):
satisfied = sum(1 for lat in latencies if lat < threshold)
tolerating = sum(1 for lat in latencies if lat >= thres…
How to Calculate Percentile Latency in Python
Generate mock latency samples with occasional spikes and compute 50th, 90th, 95th, and 99th percentile values in milliseconds.
import random
import statistics
def generate_latency_samples(n=1000):
"""Generate realistic mock latency data (ms) with occasional spikes."""
samples = []
for _ in range(n):
# Normal case: ~50ms with jitter
base = random.gauss(50, 5)
# 2% spike chance: slow downstream or GC pause
…
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.