Reference library

Python Code Samples

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

79 matches
System design patterns medium

Implement a Consistent Hash Ring in Python

Build a minimal consistent hash ring with virtual nodes to map keys to servers stably as nodes are added or removed.

consistent-hashing hashing distributed-systems
Python
import hashlib
import bisect


class ConsistentHashRing:
    def __init__(self, nodes=None, replicas=3):
        self.replicas = replicas
        self.ring = {}
        self.sorted_keys = []
        if nodes:
            for node in nodes:
                self.add_node(node)

    def _hash(self, key):
        return i…
15 0 Open
System design patterns easy

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.

routing dictionary message-broker
Python
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…
12 0 Open
Streaming & messaging easy

Exactly Once Idempotent Consumer Store in Python

A mock key-value store that guarantees exactly-once processing by rejecting duplicate message keys in a message or event stream.

idempotency streaming deduplication
Python
from collections import defaultdict

class ExactlyOnceStore:
    def __init__(self):
        self.processed = defaultdict(set)
        self.data = {}

    def consume(self, key, value):
        if key in self.data:
            return False
        self.data[key] = value
        return True

    def get_processed_count…
15 0 Open
Streaming & messaging medium

How to Simulate RabbitMQ Exchange Routing in Python

Simulate RabbitMQ exchange routing using a nested dict, matching routing keys against patterns like error.* and info.# to return bound queues.

rabbitmq routing messaging
Python
from collections import defaultdict

def route_message(exchanges, exchange_name, routing_key):
    """
    Simulate RabbitMQ exchange routing using a nested dict structure.
    Returns list of queue names that match the routing key.
    """
    queues = exchanges.get(exchange_name, {})
    matched = []
    
    for pa…
14 0 Open
Streaming & messaging easy

How to mock RabbitMQ queue binding with routing keys in Python

A mock demonstration of binding a queue to an exchange with multiple routing keys in RabbitMQ using Python and pika, without a real broker connection.

rabbitmq messaging pika
Python
import pika
import sys


def bind_queue_with_routing(channel, queue_name, exchange_name, routing_keys):
    """
    Mock RabbitMQ queue binding with routing keys.
    Prints the binding configuration instead of connecting to a real broker.
    """
    for routing_key in routing_keys:
        binding = {
            "q…
14 0 Open
Caching & Redis easy

Cache Asides in Python with a Read-Through Loader

Implements a cache-aside pattern with a read-through loader that fetches missing keys from a backing data store and caches them.

caching cache-aside read-through
Python
class DataStore:
    """Mock database with a few records."""
    def __init__(self):
        self.data = {1: "Alice", 2: "Bob", 3: "Charlie"}

    def get(self, key):
        print(f"Loading key {key} from database")
        return self.data.get(key)


class CacheAsideLoader:
    """Cache-aside pattern with a read-thr…
16 0 Open
Caching & Redis easy

Cache Warming with Python: Preload Hot Keys

Demonstrates a simple LRU-like cache with a warm method that preloads hot keys with mock values using OrderedDict.

caching ordereddict lru
Python
import time
from collections import OrderedDict

class CacheWarm:
    def __init__(self, capacity=3):
        self.capacity = capacity
        self.cache = OrderedDict()
        self.hot_keys = []

    def warm(self, keys):
        """Preload hot keys into cache with mock values."""
        for key in keys:
          …
17 0 Open
Caching & Redis medium

Consistent Hashing Cache Shard in Python

A minimal consistent hashing ring with virtual nodes that distributes cache keys across shards and minimizes re-mapping when a node is removed.

caching sharding consistent-hashing
Python
import hashlib
import bisect


class ConsistentHashRing:
    def __init__(self, nodes=None, replicas=3):
        self.replicas = replicas
        self.ring = {}
        self.sorted_keys = []
        if nodes:
            for node in nodes:
                self.add_node(node)

    def _hash(self, key):
        return i…
16 0 Open
Caching & Redis medium

How to Build a Bloom Filter to Reduce Cache Misses in Python

Implement a probabilistic Bloom filter in Python that lets a cache quickly determine which keys are definitely not present, reducing expensive source lookups on cache misses.

bloom-filter caching probabilistic
Python
import hashlib
import random

class BloomFilter:
    def __init__(self, size=100, num_hashes=3):
        self.size = size
        self.num_hashes = num_hashes
        self.bit_array = [0] * size

    def _hashes(self, item):
        result = []
        for i in range(self.num_hashes):
            hash_value = int(hash…
14 0 Open
Caching & Redis easy

How to Implement Namespaced Cache Keys for Tenant Isolation in Python

Build a tenant-aware cache wrapper that prefixes keys with tenant and namespace, and test it with mocks.

cache tenant namespace
Python
from keyvaluestore import SimpleCache
from unittest.mock import patch

class TenantCache(SimpleCache):
    def __init__(self, tenant_id, namespace="default"):
        super().__init__()
        self.tenant_id = tenant_id
        self.namespace = namespace

    def _key(self, key):
        return f"tenant:{self.tenant_…
17 0 Open
Caching & Redis medium

How to Implement a Negative Cache with TTL in Python

This code provides a TTL mock cache that stores negative results (cache misses) for a short time to reduce repeated lookups of missing keys.

cache ttl negative-cache
Python
from time import time, sleep

class TTLMockCache:
    def __init__(self, ttl_seconds=5):
        self.ttl = ttl_seconds
        self.store = {}
        self.negative_cache = {}

    def get(self, key):
        now = time()
        if key in self.store:
            value, expires_at = self.store[key]
            if exp…
13 0 Open
Caching & Redis easy

How to Iterate Redis Keys with SCAN in Python

Iterate all Redis keys matching a pattern using the SCAN command with a mock client to simulate pagination.

redis scan keys
Python
import redis

def scan_keys(client, pattern="*", count=10):
    keys = []
    cursor = 0
    while True:
        cursor, batch = client.scan(cursor=cursor, match=pattern, count=count)
        keys.extend(batch)
        if cursor == 0:
            break
    return keys

if __name__ == "__main__":
    # Mock Redis clien…
15 0 Open
Caching & Redis easy

How to use Redis MGET MSET pipeline in Python

Store multiple keys atomically and read them efficiently with Redis MSET/MGET, then batch commands with a pipeline to cut round trips.

redis mget mset
Python
import redis  # v4.x+ required

r = redis.Redis(host="localhost", port=6379, db=0, decode_responses=True)

# Sample data to store
r.flushdb()
data = {"name": "Alice", "age": "30", "city": "Berlin"}

# MSET: store multiple key-value pairs in one command
r.mset(data)

# MGET: fetch multiple keys in one round trip
keys =…
15 0 Open
Observability & SRE easy

How to Mock a Baggage Context (Key-Value Store) in Python

This code implements an in-memory key-value mock of a baggage context, letting you set, get, check, and delete keys for tracing-style metadata.

baggage tracing mock
Python
class BaggageContext:
    def __init__(self):
        self._store = {}

    def set(self, key, value):
        self._store[key] = value
        return value

    def get(self, key, default=None):
        return self._store.get(key, default)

    def has(self, key):
        return key in self._store

    def delete(sel…
15 0 Open
Observability & SRE easy

How to Redact Secrets from Log Messages in Python

Build a lightweight RedactingFormatter class that replaces sensitive tokens like passwords and API keys with [REDACTED] before log messages are printed.

redaction logging secrets
Python
class RedactingFormatter:
    def __init__(self, secrets):
        self.secrets = secrets

    def redact(self, message):
        for secret in self.secrets:
            message = message.replace(secret, "[REDACTED]")
        return message

    def format(self, record):
        message = record["message"]
        ret…
12 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
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
Big data & Spark easy

Partition Data by Hash Key Mod N in Python

Returns a partition index for a string key by hashing it with MD5 and taking modulo N, then groups sample keys into partitions.

hashing partitioning hashlib
Python
import hashlib


def partition_key(key: str, num_partitions: int) -> int:
    """Return partition index for key using MD5 hash mod N."""
    digest = hashlib.md5(key.encode()).hexdigest()
    return int(digest, 16) % num_partitions


if __name__ == "__main__":
    keys = ["alice", "bob", "carol", "dave", "eve"]
    nu…
12 0 Open
Big data & Spark medium

Skew Join Salting Key in Python (Demo)

Demonstrates skew join salting by expanding a smaller side with salt keys and matching rows on the larger side via random salt assignment.

skew join salting distributed
Python
import random


def skew_join_salting_key(left_df, right_df, salt_range=4):
    """
    Demonstrates skew join salting: expand the smaller side with salt keys,
    then attach a salt key to each row on the larger side.
    Returns a list of (left, right, salt) tuples.
    """
    skewed_left = []
    for row in left_d…
14 0 Open
A/B testing & experimentation easy

How to Create a Mock That Returns Inverse Counter Values in Python

Builds a Mock whose side_effect returns the inverse (1/count) of each Counter value, defaulting to 0.0 for unseen keys.

mock counter testing
Python
from collections import Counter
from unittest.mock import Mock

def inverse_mock(counter: Counter) -> Mock:
    """
    Return a Mock that mimics the inverse of a Counter:
    each key returns a value representing the inverse of its count.
    The Mock's side_effect maps keys to their inverse counts.
    """
    mock …
13 0 Open
Database scaling & optimization hard

B-Tree Insert and In-Order Traversal in Python

Simulates a B-tree (order 2) with insert and split logic, then prints keys in sorted order via in-order traversal.

b-tree tree data-structure
Python
class BTreeNode:
    def __init__(self, leaf=False):
        self.leaf = leaf
        self.keys = []
        self.children = []

    def is_full(self, t):
        return len(self.keys) == 2 * t - 1


class BTree:
    def __init__(self, t=2):
        self.t = t
        self.root = BTreeNode(leaf=True)

    def insert(s…
14 0 Open
Database scaling & optimization easy

Build a Partial Index Mock in Python for Database Filtering

Simulate a partial database index by filtering keys with a predicate, then return a limited mock lookup dictionary.

partial-index database mock
Python
data = [
    "alpha", "beta", "gamma", "delta", "epsilon",
    "zeta", "eta", "theta", "iota", "kappa"
]

filtered_keys = [item for item in data if len(item) >= 5]

def mock_partial_index(keys, filter_func, limit=3):
    result = {}
    for key in keys:
        if not filter_func(key):
            continue
        res…
12 0 Open
Database scaling & optimization medium

How to Build a Shard Map Mock Dict in Python

Implement a dictionary-like class that distributes keys across multiple shards using Python's hash() for realistic data partitioning.

dict sharding hash
Python
class ShardMap:
    def __init__(self, shard_count):
        self.shards = {i: {} for i in range(shard_count)}
        self.shard_count = shard_count

    def _shard_for(self, key):
        return hash(key) % self.shard_count

    def __getitem__(self, key):
        return self.shards[self._shard_for(key)][key]

    d…
14 0 Open
Database scaling & optimization medium

How to Implement Consistent Hashing in Python

Build a consistent hash ring in Python that distributes keys across nodes and minimizes remapping when nodes are added or removed.

consistent-hashing distributed-systems sharding
Python
import hashlib
from bisect import bisect_right


class ConsistentHashRing:
    def __init__(self, nodes, replicas=3):
        self.replicas = replicas
        self.ring = {}
        self.sorted_keys = []
        for node in nodes:
            self.add_node(node)

    def _hash(self, key):
        return int(hashlib.md…
15 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.