Reference library

Python Code Samples

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

60 matches
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 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 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 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
Big data & Spark easy

Cache persist MEMORY_ONLY mock in Python

Mock a MEMORY_ONLY persistence cache in Python with an LRU eviction policy and optional persistence flag.

cache lru mock
Python
import time

class LRUCache:
    def __init__(self, capacity, persistence="MEMORY_ONLY"):
        self.capacity = capacity
        self.persistence = persistence
        self.cache = {}
        self.access_order = []
        self.hits = 0
        self.misses = 0

    def get(self, key):
        if key in self.cache:
 …
13 0 Open
ML engineering pipelines easy

How to Build a Mock Offline Feature Store in Python

Build an in-memory mock of an offline feature store with a dict-based FeatureStore class for storing and retrieving ML features by entity ID.

feature-store ml-pipeline mock
Python
from datetime import datetime
from collections import defaultdict


class FeatureStore:
    """Simple in-memory mock of an offline feature store."""

    def __init__(self):
        self._features = defaultdict(dict)

    def ingest(self, entity_id, feature_name, value, timestamp=None):
        ts = timestamp or datet…
14 0 Open
ML engineering pipelines easy

Model registry version mock in Python

A simple in-memory model registry that stores model versions with metadata and supports version listing and latest retrieval.

ml-engineering model-registry versioning
Python
class ModelRegistry:
    def __init__(self):
        self.models = {}

    def register(self, name, version, model_type, metrics=None):
        if name not in self.models:
            self.models[name] = []
        entry = {
            "version": version,
            "model_type": model_type,
            "metrics": m…
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 easy

How to Insert a Mock Route Record Using SQLite in Python

This code creates an in-memory SQLite table for routes and inserts a mock route record, returning the inserted row for verification.

sqlite database insert
Python
import sqlite3
from datetime import datetime

def insert_mock_record(db_path=":memory:"):
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    cursor.execute("""
        CREATE TABLE IF NOT EXISTS routes (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            origin TEXT NOT NULL,
            des…
14 0 Open
Auth & security at scale easy

Fetch Secrets from a Mock Secrets Manager in Python

Build a minimal in-memory secrets manager that stores and retrieves secret values, raising a KeyError for missing names.

secrets-management security mock
Python
import json

class SecretsManager:
    """Mock secrets manager that returns secrets from a local store."""
    
    def __init__(self, store=None):
        self.store = store or {
            "api_key": "mock-api-key-123",
            "db_password": "s3cret-p@ss",
            "jwt_secret": "dev-only-secret"
        }
…
16 0 Open
Production deployment patterns easy

How to Mock a Container Registry in Python

Build an in-memory container registry mock with push, tag listing, and manifest retrieval logic for testing deployment tooling.

containers testing mocking
Python
import json
from collections import defaultdict


class MockRegistry:
    def __init__(self):
        self.repositories = defaultdict(dict)

    def push_image(self, repo: str, tag: str, layers: list[str]) -> None:
        self.repositories[repo][tag] = {
            "layers": layers,
            "size": sum(len(layer…
14 0 Open
Production deployment patterns easy

How to mock resource request limits in Python

A Python class that simulates CPU and memory limit checks for resource requests, returning clear acceptance or rejection messages.

resource-limits mock class
Python
class ResourceLimits:
    def __init__(self, cpu_limit, memory_limit):
        self.cpu_limit = cpu_limit
        self.memory_limit = memory_limit

    def check_request(self, cpu, memory):
        if cpu > self.cpu_limit:
            return "CPU limit exceeded: {cpu} > {limit}".format(cpu=cpu, limit=self.cpu_limit)
 …
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.