Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Use the Adapter Pattern to Mock a Legacy System in Python
This code demonstrates the Adapter pattern, allowing a modern interface to interact with a legacy system by wrapping its outdated method.
class LegacySystem:
def legacy_method(self, data):
return f"Legacy processed: {data}"
class ModernInterface:
def process(self, data):
raise NotImplementedError
class Adapter(ModernInterface):
def __init__(self, legacy):
self.legacy = legacy
def process(self, data):
re…
How to implement a circuit breaker in Python
A Python CircuitBreaker class that tracks failures, opens after a threshold, and retries after a timeout.
class CircuitBreaker:
def __init__(self, failure_threshold=3, timeout=5):
self.failure_threshold = failure_threshold
self.timeout = timeout
self.failure_count = 0
self.last_failure_time = None
self.state = "CLOSED"
def call(self, mock_downstream):
if self.state …
How to implement read-your-writes sticky routing in Python
A mock StickyRouter class that routes all requests for the same key to the same node, ensuring read-after-write consistency.
import random
class StickyRouter:
def __init__(self, nodes):
self.nodes = nodes
self.routes = {}
def route(self, key):
if key not in self.routes:
self.routes[key] = random.choice(self.nodes)
return self.routes[key]
def read(self, key):
node = self.rout…
How to implement round-robin load balancing in Python
Implement a client-side round-robin load balancer that distributes requests sequentially across a list of mock servers using itertools.cycle.
import itertools
import random
class MockServer:
def __init__(self, name):
self.name = name
def handle_request(self, request_id):
return f"Server {self.name} handled request #{request_id}"
class RoundRobinLoadBalancer:
def __init__(self, servers):
self.servers = servers
…
How to implement the Database per service pattern in Python
Simulate separate databases per microservice in Python using dataclasses and in-memory dictionaries, showing how services own their data independently.
import json
from dataclasses import dataclass, asdict
from typing import Dict, List
@dataclass
class User:
id: int
name: str
email: str
@dataclass
class Order:
id: int
user_id: int
product: str
amount: float
class UserServiceDB:
"""Simulates a separate database for the User servic…
How to mock a SPIFFE workload identity in Python
Generate a mock SPIFFE ID and token for a workload using a trust domain, namespace, and service account.
import hashlib
import json
from dataclasses import dataclass, asdict
@dataclass
class SPIFFEIdentity:
trust_domain: str
namespace: str
service_account: str
@property
def id(self) -> str:
return f"spiffe://{self.trust_domain}/ns/{self.namespace}/sa/{self.service_account}"
def mock_workl…
How to mock an external service in Python with an anti-corruption facade
This code implements an anti-corruption facade that mocks an external API, allowing client code to interact with a simulated service while keeping the same interface.
class AntiCorruptionFacade:
"""Mocks a real API while keeping the same interface."""
def __init__(self, data_store):
self._data_store = data_store
self._calls = []
def get_user(self, user_id):
self._calls.append(f"get_user({user_id})")
return self._data_store.get(u…
Idempotent Consumer Event Processing in Python
Track processed event IDs to skip duplicates and count event types for a reliable, idempotent consumer.
import json
from collections import defaultdict
class EventProcessor:
def __init__(self):
self.processed_ids = set()
self.counts = defaultdict(int)
def process_event(self, event):
event_id = event["id"]
if event_id in self.processed_ids:
return {"status": "skipped"…
JWT Service-to-Service Authentication Mock in Python
Create and verify HS256 JWTs for service-to-service authentication without external libraries.
import hashlib
import hmac
import base64
import json
import time
class JWTMock:
"""Minimal JWT service-to-service mock using HS256."""
def __init__(self, secret):
self.secret = secret.encode()
@staticmethod
def _b64url_encode(data):
return base64.urlsafe_b64encode(data).rstr…
Mock a Sidecar Logger with Python Metrics
Simulate a sidecar logger that tracks request counts, error rates, and endpoint hits, producing a metrics snapshot.
import random
import time
from collections import defaultdict
class SidecarLogger:
def __init__(self):
self.metrics = defaultdict(int)
self.total_requests = 0
self.error_count = 0
def log_request(self, endpoint, status_code):
"""Simulate logging a request and updating metrics…
Python Saga Compensating Steps Mock
Mock a distributed transaction saga with forward steps and compensating actions that reverse partial progress on failure.
from datetime import datetime
def make_payment(user_id, amount):
print(f"[{datetime.now():%H:%M:%S}] Payment of ${amount} processed for user {user_id}")
return {"step": "payment", "status": "ok", "details": f"${amount} charged"}
def deduct_inventory(order_id, items):
print(f"[{datetime.now():%H:%M:%S}]…
Saga pattern orchestration with rollback in Python
Orchestrate a distributed transaction with Saga steps and automated compensation rollback on failure.
import time
import random
class SagaStep:
def __init__(self, name):
self.name = name
self.executed = False
def execute(self):
print(f"Executing {self.name}...")
time.sleep(0.2)
if random.random() < 0.3:
raise RuntimeError(f"{self.name} failed")
sel…
Strangler Fig Migration Pattern in Python
Gradually reroute calls from a legacy service to a modern replacement using a runtime switch and feature detection.
from dataclasses import dataclass
@dataclass
class PaymentService:
def process(self, amount: float) -> str:
return f"Legacy processed ${amount:.2f}"
class StranglerFig:
def __init__(self):
self._new_service = None
def attach_new(self, service):
self._new_service = service
de…
Zero Trust Service Auth Mock in Python
A simple HMAC-based token issuance and validation mock that enforces zero trust between microservices.
import hmac
import hashlib
import json
import time
class ZeroTrustAuth:
def __init__(self, secret_key):
self.secret_key = secret_key
self.service_tokens = {}
def issue_token(self, service_name, ttl=300):
payload = {
"service": service_name,
"issued_at": int(tim…
Generate a docker-compose.yml with mock services in Python
Build a docker-compose.yml string from a Python dict of service names and images, then write it to a file.
import yaml
from pathlib import Path
def generate_mock_compose(services: dict) -> str:
compose = {
"version": "3.9",
"services": {}
}
for name, image in services.items():
compose["services"][name] = {
"image": image,
"container_name": f"mock-{name}",
…
How to Mock Kubernetes Services with a ClusterIP Registry in Python
Simulate Kubernetes service discovery by assigning ClusterIP addresses to dataclass-defined services, with JSON export for inspection or testing.
import json
from dataclasses import dataclass, asdict
from typing import Dict, Optional
@dataclass
class Service:
name: str
namespace: str
cluster_ip: str
selector: Dict[str, str]
port: int
target_port: Optional[int] = None
class ClusterIPServiceRegistry:
_ip_counter = 0
def __init…
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.