Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

77 matches
System design patterns easy

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.

onion-architecture repository-pattern dependency-injection
Python
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]:
     …
11 0 Open
Streaming & messaging easy

Dedupe processed message IDs in Python

Filters an inbox of messages by removing items whose IDs have already been processed, using a set for fast lookups.

deduplication streaming json
Python
from pathlib import Path
import json


def dedupe_processed_ids(inbox_file: Path, processed_file: Path) -> list:
    processed = set(json.loads(processed_file.read_text()))
    inbox = json.loads(inbox_file.read_text())
    deduped = [item for item in inbox if item["id"] not in processed]
    return deduped


if __nam…
13 0 Open
Streaming & messaging medium

How to Encode and Decode Avro Data in Python (Roundtrip)

Serialize a Python dict to Avro binary bytes and decode it back using the fastavro-compatible avro library.

avro serialization encode
Python
import io
import json
from avro.schema import parse
from avro.io import DatumWriter, DatumReader, BinaryEncoder, BinaryDecoder

def avro_roundtrip(schema_json, data):
    schema = parse(json.dumps(schema_json))
    bytes_writer = io.BytesIO()
    encoder = BinaryEncoder(bytes_writer)
    writer = DatumWriter(schema)
 …
14 0 Open
Streaming & messaging medium

How to Implement At-Least-Once Delivery with Acknowledgment in Python

This code demonstrates a mock message broker with at-least-once delivery, including retry logic and acknowledgment after successful processing.

messaging queue retry
Python
import time
import uuid
from collections import deque


class MockMessageBroker:
    def __init__(self):
        self.queue = deque()
        self.acked = set()

    def publish(self, payload: str) -> str:
        msg_id = str(uuid.uuid4())
        self.queue.append((msg_id, payload))
        return msg_id

    def po…
13 0 Open
Streaming & messaging easy

How to Implement Publish-Subscribe Fanout with Multiple Subscribers in Python

Create a simple publish-subscribe system in Python that broadcasts messages to multiple subscriber callbacks for a given topic.

pubsub messaging events
Python
import time

class PubSub:
    def __init__(self):
        self.subscribers = {}

    def subscribe(self, topic, callback):
        if topic not in self.subscribers:
            self.subscribers[topic] = []
        self.subscribers[topic].append(callback)

    def publish(self, topic, message):
        if topic in sel…
14 0 Open
Streaming & messaging easy

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.

pubsub event-driven design-pattern
Python
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…
18 0 Open
Caching & Redis medium

How to Implement an LFU Cache in Python

Implement a Least Frequently Used (LFU) cache with frequency tracking dictionaries to evict the least accessed items when capacity is reached.

lfu cache frequency
Python
class LFUCache:
    def __init__(self, capacity: int):
        self.capacity = capacity
        self.data = {}
        self.freq = {}
        self.min_freq = 0

    def get(self, key: int) -> int:
        if key not in self.data:
            return -1
        self._increment_freq(key)
        return self.data[key]

  …
12 0 Open
Reliability & rate limiting medium

At Least Once with Idempotent Consumer in Python

Implements a thread-safe idempotent consumer that processes each unique message exactly once, even when a producer sends duplicates under an at-least-once delivery model.

idempotency at-least-once threading
Python
import threading
import time
import uuid
from collections import Counter


class IdempotentConsumer:
    def __init__(self):
        self.processed = set()
        self._lock = threading.Lock()

    def consume(self, message_id, payload):
        with self._lock:
            if message_id in self.processed:
          …
16 0 Open
Reliability & rate limiting medium

How to Cap Retry Attempts in Python with a Decorator

Build a reusable retry decorator that caps attempts, adds delays, and lets flaky services fail fast instead of hanging.

retry decorator resilience
Python
import random
from functools import wraps
from time import sleep


def retry(max_attempts, delay=0.1):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            attempts = 0
            while attempts < max_attempts:
                try:
                    return func(*args, **kw…
13 0 Open
Reliability & rate limiting easy

How to Deduplicate Messages in Python by ID

This code consumes a mock inbox of JSON messages and deduplicates them by message ID, keeping either the first or last occurrence.

deduplication inbox json
Python
import json
from collections import OrderedDict

mock_inbox = [
    {"id": 1, "message": "hello", "timestamp": "2024-01-01T10:00:00Z"},
    {"id": 2, "message": "world", "timestamp": "2024-01-01T10:01:00Z"},
    {"id": 1, "message": "hello", "timestamp": "2024-01-01T10:00:00Z"},
    {"id": 3, "message": "test", "times…
15 0 Open
Reliability & rate limiting medium

How to Implement a Circuit Breaker in Python

A Python dataclass that provides circuit breaker logic with closed, open, and half-open states to fail fast on repeated errors.

circuit-breaker resilience fault-tolerance
Python
from dataclasses import dataclass
from datetime import datetime, timedelta
import time


@dataclass
class CircuitBreaker:
    failure_threshold: int = 3
    timeout_seconds: float = 5.0
    failures: int = 0
    state: str = "closed"
    last_failure: datetime = None

    def call(self, func):
        if self.state ==…
15 0 Open
Reliability & rate limiting medium

Implement a Circuit Breaker Pattern in Python

This code implements a simple circuit breaker that opens after a threshold of consecutive failures, causing subsequent calls to fail fast without invoking the underlying function.

circuit-breaker reliability resilience
Python
class CircuitBreaker:
    def __init__(self, failure_threshold=3):
        self.failure_threshold = failure_threshold
        self.failure_count = 0
        self.open = False

    def call(self, func, *args, **kwargs):
        if self.open:
            raise RuntimeError("Circuit is open - failing fast")
        try:
…
15 0 Open
Reliability & rate limiting easy

Implementing Fallback with Cached Stale Data in Python

This code demonstrates a resilient data-fetching pattern that caches successful responses, falls back to cached data when the external API fails, and returns stale data as a last-resort fallback.

cache fallback resilience
Python
import random
import time

# Simulated cache dictionary: key -> (value, timestamp)
_cache = {}
_CACHE_TTL = 3  # seconds

# Mock data source (simulates an unreliable external API)
def fetch_mock_data(key):
    failure = random.random() < 0.4  # 40% chance of failure
    if failure:
        raise ConnectionError("Mock …
14 0 Open
Reliability & rate limiting medium

Retry with Exponential Backoff and Jitter in Python

A decorator-style retry wrapper that retries a flaky function with exponential backoff plus random jitter, then raises after the last attempt fails.

retry backoff jitter
Python
import random
import time

def retry_with_backoff(func, max_retries=3, base_delay=0.5, max_jitter=0.1):
    for attempt in range(max_retries + 1):
        try:
            return func()
        except Exception as e:
            if attempt == max_retries:
                raise
            delay = base_delay * (2 ** at…
14 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
Big data & Spark easy

How to Broadcast a Small Lookup Table in Python

Simulates broadcasting a small lookup table by iterating key-value pairs and emitting packed rows to subscribers with deterministic output.

broadcast lookup-table dictionary
Python
import random

# Generate a deterministic mock broadcast of a small lookup table
# with 5 keys and random integer values (seeded for reproducibility)

data = {
    "sensor_a": 22,
    "sensor_b": 87,
    "sensor_c": 43,
    "sensor_d": 65,
    "sensor_e": 31,
}

# Simulate a broadcast to subscribers by iterating and p…
14 0 Open
Big data & Spark easy

How to Use Broadcast Variables as Read-Only in PySpark (Mock Example)

Share a lookup dict across Spark executors with a broadcast variable and verify its read-only behavior in a local mock.

pyspark broadcast spark
Python
from pyspark import SparkContext, SparkConf

def main():
    conf = SparkConf().setAppName("BroadcastMock").setMaster("local[2]")
    sc = SparkContext(conf=conf)
    
    lookup = {"a": 1, "b": 2, "c": 3}
    broadcast_lookup = sc.broadcast(lookup)
    
    data = ["a", "b", "c", "a", "unknown"]
    rdd = sc.parallel…
13 0 Open
Big data & Spark easy

Modeling a Hive Metastore Table Schema in Python

A dataclass that mimics a Hive metastore table schema—columns, partition keys, storage format, and location—with helper methods for description and mutation.

hive dataclass metastore
Python
from dataclasses import dataclass, field
from typing import Dict, List, Optional


@dataclass
class HiveTable:
    """Simple mock of a Hive metastore table schema."""
    name: str
    database: str = "default"
    columns: List[Dict[str, str]] = field(default_factory=list)
    partition_keys: List[Dict[str, str]] = f…
14 0 Open
ML engineering pipelines easy

How to Mock a Feature Store Online Lookup in Python

This code simulates an online feature store with single and batch retrieval methods, using a dict-backed cache and timestamps.

feature-store ml-infrastructure online-lookup
Python
import random
import time


class OnlineFeatureStore:
    def __init__(self):
        self.features = {}

    def put(self, entity_id: str, feature_name: str, value):
        key = (entity_id, feature_name)
        self.features[key] = (value, time.time())

    def get(self, entity_id: str, feature_name: str):
       …
13 0 Open
Database scaling & optimization easy

Broadcast a Small Reference Table in Python

Simulates SQL-style broadcasting of a small lookup table against a larger fact table in memory for mockups or load tests.

broadcast mock-data data-engineering
Python
import random

def broadcast_mock(target, source, columns):
    result = {}
    for col in columns:
        if col in target and col in source:
            result[col] = target[col] + [source[col][i % len(source[col])] for i in range(len(target[col]))]
        elif col in target:
            result[col] = target[col]
…
15 0 Open
Database scaling & optimization medium

How to Implement Keyset Pagination in Python (Seek Method)

Implement keyset (seek) pagination in Python with a mock paginator that efficiently fetches pages based on the last row rather than OFFSET.

pagination keyset seek-method
Python
from dataclasses import dataclass
from typing import List, Optional


@dataclass
class Row:
    id: int
    name: str

    def __lt__(self, other: "Row") -> bool:
        return (self.id, self.name) < (other.id, other.name)


class MockKeysetPaginator:
    """Pagination using keyset (seek) method instead of OFFSET."""…
14 0 Open
Database scaling & optimization easy

How to Mock Sticky Session Read-Your-Writes in Python

Simulates a sticky session store that routes reads for a session to the node where the last write occurred, demonstrating read-your-writes consistency.

sticky sessions read-your-writes mock
Python
class StickySessionStore:
    def __init__(self):
        self.data = {}
        self.session_nodes = {}

    def write(self, session_id, key, value):
        self.data[key] = value
        self.session_nodes[session_id] = key
        return f"Wrote {key}={value} for session {session_id}"

    def read(self, session_i…
13 0 Open
Database scaling & optimization easy

How to Speed Up Column Lookups with DataFrame Index in Python

Use pandas set_index to make repeated column value lookups O(1)-style fast instead of scanning the whole DataFrame each time.

pandas indexing performance
Python
import pandas as pd

# Mock dataset with duplicate customer IDs
data = {"customer_id": [101, 102, 103, 101, 104, 102],
        "order_amount": [250.0, 85.5, 300.0, 175.25, 420.0, 95.75]}

df = pd.DataFrame(data)
df = df.set_index("customer_id")

# Simulated lookup request
search_id = 102

# Fast index-based lookup (no…
15 0 Open
Database scaling & optimization medium

Simulate a GIN Index for JSONB in Python

Build a mock Generalized Inverted Index (GIN) that flattens JSON documents into key-value tokens for fast lookup queries, mimicking PostgreSQL JSONB indexing.

jsonb gin-index inverted-index
Python
import json
import random
from collections import defaultdict

# Mock GIN (Generalized Inverted Index) for JSONB key-value pairs
class GINIndex:
    def __init__(self):
        self.posting_lists = defaultdict(list)  # token -> list of doc_ids
    
    def index(self, doc_id, json_obj):
        """Index a JSON documen…
14 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.