Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Build a Microservice Helper in Python
A beginner-friendly Python helper that validates input, normalizes service responses, and simulates user management—showing clean patterns for microservice development.
import json
from typing import Any, Dict, List
class DataValidator:
"""Simple validator for common data patterns."""
@staticmethod
def is_valid_email(value: str) -> bool:
"""Check if value looks like an email."""
return "@" in value and "." in value.split("@")[-1]
@staticmethod
…
How to Build an Anti-Corruption Layer in Python
Translate messy legacy system data into a clean domain model using an anti-corruption layer in Python.
class MockLegacySystem:
"""Simulates a legacy system with messy data formats."""
def get_user_data(self):
# Legacy format: fields are abbreviated and types are inconsistent
return {
"usr_id": "USR-123",
"usr_nm": "john_doe",
"email_addrs": "John.Doe@example.c…
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.
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]
…
How to Build an OAuth Client Credentials Mock Server in Python
A minimal HTTP mock server implementing the OAuth 2.0 client credentials grant for local testing and microservice development.
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
TOKENS = {"valid_token": "demo_access_token", "client_id": "my_service"}
class OAuthHandler(BaseHTTPRequestHandler):
def do_POST(self):
if self.path == "/oauth/token":
length = int(self.headers.get("Content-Length", 0))
…
How to Check an External Gateway vs Use an Internal Mock in Python
This code checks whether an external network gateway is reachable using ping, then falls back to a deterministic internal mock for testing environments.
import subprocess
import sys
def check_external_gateway():
"""True if we can reach an external network target."""
try:
subprocess.run(
["ping", "-c", "1", "-W", "2", "8.8.8.8"],
capture_output=True,
timeout=3,
check=True,
)
return True
…
How to Compose Parallel API Calls in Python with asyncio.gather
Compose multiple mock API responses in parallel using asyncio.gather with per-service simulated latency.
import asyncio
import random
import time
async def mock_api(name: str, delay: float) -> dict:
await asyncio.sleep(delay)
return {"service": name, "value": random.randint(1, 100)}
async def fetch_all():
services = {
"users": mock_api("users", 0.2),
"orders": mock_api("orders", 0.3),
…
How to Deduplicate Events in Python with SHA256 Hashing
Build an event deduplicator that identifies duplicate inbox messages using SHA256 hashes and tracks duplicate counts per event type.
```python
import hashlib
import json
from collections import defaultdict
class EventDeduplicator:
def __init__(self):
self.seen_hashes = set()
self.duplicate_counts = defaultdict(int)
def process_event(self, event):
event_key = f"{event['event_id']}:{event['timestamp']}"
even…
How to Demonstrate the Shared Database Antipattern in Python
This code simulates a shared database where multiple services write and read the same SQLite table, illustrating tight coupling and its pitfalls.
import sqlite3
from pathlib import Path
def create_shared_db(db_path: Path) -> None:
"""Mock demonstrating the shared database antipattern where multiple
services access the same database, causing tight coupling."""
conn = sqlite3.connect(db_path)
cur = conn.cursor()
cur.execute("""
CREATE…
How to Handle mTLS Certificate Rotation in Python
Detect mTLS certificate file changes by tracking modification time and hot-reload the SSL context in a running service.
import ssl
import tempfile
import datetime
from pathlib import Path
class MTLSContext:
def __init__(self, cert_path, key_path, ca_path):
self.cert_path = Path(cert_path)
self.key_path = Path(key_path)
self.ca_path = Path(ca_path)
self.context = None
self.last_loaded_mtime …
How to Implement a Data Helper for Microservices in Python
Create a reusable helper class to serialize, deserialize, and wrap data for microservice communication using dataclasses and JSON.
import json
from dataclasses import dataclass, asdict
from typing import Any, Dict, List
@dataclass
class ServiceResponse:
status: str
data: Any
message: str = ""
class DataHelper:
"""Simple helper for microservice data handling."""
@staticmethod
def serialize(data: Dict[str, Any]) -> str:…
How to Implement a Two-Phase Commit Mock in Python
Simulate a distributed two-phase commit with prepare, commit, and abort phases, including deterministic failure injection for testing.
import random
from dataclasses import dataclass
from typing import Dict, List, Optional
@dataclass
class Transaction:
tx_id: int
data: Dict[str, str]
class TwoPhaseCommitMock:
"""Simple two-phase commit mock with prepare and commit phases."""
def __init__(self) -> None:
self.prepared: List…
How to Implement an Exactly-Once Deduplication Store in Python
Implement a Python class that deduplicates keys exactly once, tracking first-seen timestamps and duplicate counts.
from datetime import datetime
from typing import Any, Hashable
class ExactlyOnceStore:
def __init__(self) -> None:
self._seen: set[Hashable] = set()
self._first_seen: dict[Hashable, datetime] = {}
self._counts: dict[Hashable, int] = {}
def add(self, key: Hashable, value: Any = None) …
How to Implement an Outbox Pattern Mock in Python
This code demonstrates a simple in-memory outbox pattern mock for publishing domain events and tracking pending events until they are marked as published.
from dataclasses import dataclass, field
from datetime import datetime
from uuid import uuid4
@dataclass
class DomainEvent:
event_id: str = field(default_factory=lambda: str(uuid4()))
occurred_at: datetime = field(default_factory=datetime.utcnow)
class Outbox:
def __init__(self):
self._events =…
How to Mock Eventual Consistency UI Notes in Python
Simulates a UI note that shows local state until a pending server update is confirmed, mocking eventual consistency behavior in distributed systems.
class EventualConsistencyNote:
def __init__(self, entity_id, note):
self.entity_id = entity_id
self.note = note
self.confirmed = False
self.pending_updates = []
def add_pending_update(self, update):
self.pending_updates.append(update)
def confirm_update(self):
…
How to Mock Service Call Timeouts in Python
Simulate service calls with configurable timeouts using Mock to patch sleep and randomness, covering success and timeout cases.
import time
from unittest.mock import Mock, patch
# Simulate a service call with configurable timeout
def call_service(service_name, timeout=5):
"""Mock a service call that may time out."""
start = time.time()
print(f"Calling {service_name}...")
# Simulate service latency (randomized for realism)…
How to Mock Service Versioning URI in Python
Run a minimal HTTP server in Python that routes requests to different versions of a service URI like /v1/users vs /v2/users.
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
class VersionedHandler(BaseHTTPRequestHandler):
def _send_json(self, payload, status=200):
body = json.dumps(payload).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
…
How to Mock a Choreography Saga in Python
Simulate a choreography-based saga with event envelopes, status tracking, and compensating actions to model distributed transactions.
import json
from dataclasses import dataclass, asdict
from typing import List, Optional
from enum import Enum
class SagaStatus(Enum):
PENDING = "PENDING"
COMPLETING = "COMPLETING"
COMPLETED = "COMPLETED"
FAILED = "FAILED"
@dataclass
class EventEnvelope:
event_type: str
order_id: str
sta…
How to Mock a GraphQL Backend in Python
Create an in-memory GraphQL mock backend using dataclasses and resolver methods returning plain dictionaries.
from dataclasses import dataclass, asdict
from typing import Any, Dict, List
@dataclass
class Product:
id: int
name: str
price: float
@dataclass
class User:
id: int
username: str
class MockGraphQLBackend:
def __init__(self) -> None:
self.products = [
Product(id=1, name…
How to Mock a Server-Side Load Balancer in Python
A simple Python class that mimics a server-side load balancer with round-robin, random, and least-connections selection strategies.
import itertools
import random
class LoadBalancer:
def __init__(self, servers=None):
self.servers = servers if servers else ["server1", "server2", "server3"]
self.counter = itertools.count(1)
def round_robin(self):
return next(self.counter) % len(self.servers)
def random_selectio…
How to Mock a Service Mesh Sidecar Proxy in Python
Simulate a service mesh sidecar proxy with route registration, service discovery, and request proxying using a simple Python class.
class SidecarProxy:
def __init__(self, name):
self.name = name
self.routes = {}
self.services = {}
self.requests_processed = 0
def register_service(self, service_name, address, port):
self.services[service_name] = f"{address}:{port}"
def add_route(self, path, servi…
How to Mock a Service Registry in Python with an In-Memory Dict
A lightweight ServiceRegistry class backed by a dict, exposing register, unregister, lookup, list, and health-check methods.
class ServiceRegistry:
def __init__(self):
self._services = {}
def register(self, name, endpoint, version="1.0"):
self._services[name] = {
"endpoint": endpoint,
"version": version,
"status": "healthy"
}
def unregister(self, name):
return…
How to Mock an API Gateway Router in Python
Create a lightweight HTTP server that routes requests to mock microservice responses, simulating an API gateway for local development and testing.
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
class SimpleGateway(BaseHTTPRequestHandler):
def do_GET(self):
routes = {
"/users": {"service": "user-service", "status": "ok", "count": 42},
"/orders": {"service": "order-service", "status": "ok", "count": 17}…
How to Mock an Ambassador Edge Proxy in Python
Build a lightweight mock Ambassador edge proxy with Python's http.server that responds to health and user endpoint requests for local development and testing.
import http.server
import json
import urllib.parse
import threading
class AmbassadorProxyHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
parsed = urllib.parse.urlparse(self.path)
if parsed.path == "/health":
self.send_response(200)
self.send_header("Content-T…
How to Mock mTLS Between Services in Python
Simulate mutual TLS authentication between two services using Python's ssl module with self-signed certificates.
import ssl
import socket
import threading
import tempfile
from pathlib import Path
import subprocess
def create_test_cert(cert_path: Path, key_path: Path, common_name: str = "localhost"):
"""Generate a self-signed certificate using openssl."""
subprocess.run([
"openssl", "req", "-x509", "-newkey", "rs…
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.