Reference library

Python Code Samples

Easy snippets you can copy, study, and run in the browser editor.

31 matches
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
Microservices patterns easy

BFF aggregation pattern: combine multiple service responses in Python

Mock three backend services and aggregate their responses into one unified payload — the BFF pattern every Python microservice gateway relies on.

bff aggregation microservices
Python
from dataclasses import dataclass
from typing import Any


@dataclass
class Service:
    name: str
    data: dict[str, Any]


def get_user_service() -> Service:
    return Service("user", {"id": 1, "name": "Alice"})


def get_orders_service() -> Service:
    return Service("orders", {"total": 299.99, "count": 2})


de…
13 0 Open
Microservices patterns easy

Cache-Aside Pattern in Python: Per-Service Mock

A Python mock of the cache-aside pattern for a single microservice—lazy-load from a database into an in-memory cache and invalidate on updates.

caching microservices cache-aside
Python
class ServiceCache:
    def __init__(self):
        self.database = {"user:1": "Alice", "user:2": "Bob", "user:3": "Charlie"}
        self.cache = {}

    def get_user(self, user_id):
        cache_key = f"user:{user_id}"
        if cache_key in self.cache:
            print(f"CACHE HIT: {cache_key}")
            retu…
13 0 Open
Microservices patterns easy

Correlation ID HTTP header mock in Python

A lightweight HTTP server that echoes or generates correlation IDs to help test distributed systems.

correlation-id http-server mock
Python
import json
import uuid
from http.server import BaseHTTPRequestHandler, HTTPServer


class CorrelationHandler(BaseHTTPRequestHandler):
    CORRELATION_HEADER = "X-Correlation-ID"

    def do_GET(self):
        correlation_id = self.headers.get(self.CORRELATION_HEADER) or str(uuid.uuid4())
        response = {
        …
13 0 Open
Microservices patterns easy

Event Sourcing Store in Python: Append-Only Log Mock

Mock an append-only event store in Python — record events, list them, and fetch by ID using a simple list-backed class.

event-sourcing microservices mock
Python
class EventStore:
    def __init__(self):
        self._events = []

    def append(self, event):
        event_id = len(self._events) + 1
        stored_event = {"id": event_id, "data": event}
        self._events.append(stored_event)
        return stored_event

    def get_events(self):
        return list(self._ev…
14 0 Open
Microservices patterns easy

How to Build a Health Check Service Registry in Python

Build a minimal Python service registry that handles registration, deregistration, health checks, and service listing in one simple class.

microservices health-check service-discovery
Python
import random
import time


class ServiceRegistry:
    def __init__(self):
        self.services = {}

    def register(self, name, address):
        self.services[name] = {
            "address": address,
            "status": "healthy",
            "registered_at": time.time(),
            "checks": 0
        }
    …
13 0 Open
Microservices patterns easy

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.

microservices validation oop
Python
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
    …
12 0 Open
Microservices patterns easy

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.

service-registry microservices in-memory
Python
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]

 …
14 0 Open
Microservices patterns easy

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.

network-check mock microservices
Python
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
  …
14 0 Open
Microservices patterns easy

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.

asyncio concurrency api
Python
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),
      …
15 0 Open
Microservices patterns easy

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.

deduplication event-processing hashing
Python
```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…
12 0 Open
Microservices patterns easy

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.

microservices database antipatterns
Python
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…
13 0 Open
Microservices patterns easy

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.

microservices json dataclass
Python
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:…
13 0 Open
Microservices patterns easy

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.

deduplication exactly-once set
Python
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) …
13 0 Open
Microservices patterns easy

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.

outbox domain-events microservices
Python
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 =…
13 0 Open
Microservices patterns easy

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.

eventual-consistency microservices ui
Python
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):
    …
17 0 Open
Microservices patterns easy

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.

http-server versioning mock
Python
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")
    …
11 0 Open
Microservices patterns easy

How to Mock a GraphQL Backend in Python

Create an in-memory GraphQL mock backend using dataclasses and resolver methods returning plain dictionaries.

graphql mock dataclasses
Python
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…
15 0 Open
Microservices patterns easy

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.

load-balancer microservices simulation
Python
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…
13 0 Open
Microservices patterns easy

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.

sidecar-proxy service-mesh microservices
Python
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…
14 0 Open
Microservices patterns easy

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.

microservices service-registry dictionary
Python
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…
13 0 Open
Microservices patterns easy

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.

api-gateway mock-server http
Python
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}…
14 0 Open
Microservices patterns easy

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.

ambassador mock http-server
Python
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…
13 0 Open
Microservices patterns easy

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.

adapter-pattern design-patterns legacy
Python
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…
13 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.