Reference library

Python Code Samples

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

55 matches
System design patterns medium

How to Apply the Clean Architecture Dependency Rule in Python

Demonstrates the dependency rule with a Protocol repository, a use case, and a presenter wired together at a composition root.

clean-architecture dependency-inversion protocol
Python
from dataclasses import dataclass
from typing import List, Protocol

class Repository(Protocol):
    def get_items(self) -> List[str]:
        ...

@dataclass
class InMemoryRepository:
    items: List[str]

    def get_items(self) -> List[str]:
        return self.items

class UseCase:
    """Application layer depends…
13 0 Open
System design patterns medium

How to Build an Adapter to Translate External API Responses in Python

Build an adapter class that translates a mock external API's response shape into your internal representation, keeping callers decoupled from the external contract.

adapter-pattern api architecture
Python
import json
from typing import Dict, Any


class ExternalAPI:
    """Mock external service returning a different data shape."""
    def get_user(self, user_id: int) -> Dict[str, Any]:
        return {
            "id": user_id,
            "full_name": "Jane Doe",
            "email_address": "jane@example.com",
     …
14 0 Open
System design patterns easy

How to Build an Append-Only Event Store in Python

Implement a simple append-only event store class that stores events in a list and supports retrieval by index range.

event-sourcing append-only event-store
Python
class EventStore:
    def __init__(self):
        self._events = []

    def append(self, event):
        """Append an event to the store."""
        self._events.append(event)

    def get_events(self, start=0, end=None):
        """Return events from start index to end (exclusive)."""
        return self._events[sta…
14 0 Open
System design patterns easy

How to Build an MVP Presenter View Mock in Python

A minimal MVP (Model-View-Presenter) mock showing a Presenter controlling a SlideDeck model with slide navigation and typed state via dataclasses.

dataclasses mvp design-patterns
Python
from dataclasses import dataclass, field
from typing import List


@dataclass
class SlideDeck:
    title: str
    slides: List[str] = field(default_factory=list)
    current_index: int = 0

    def next_slide(self) -> str:
        if self.current_index < len(self.slides) - 1:
            self.current_index += 1
      …
13 0 Open
System design patterns medium

How to Implement CQRS with Separate Read and Write Models in Python

Implements Command Query Responsibility Segregation (CQRS) by splitting data into separate write and read models with dedicated repositories, using dataclasses for structure.

cqrs dataclasses repositories
Python
from dataclasses import dataclass, field
from typing import List, Dict, Optional


@dataclass
class OrderWriteModel:
    order_id: int
    customer: str
    items: List[str] = field(default_factory=list)

    def add_item(self, item: str) -> None:
        self.items.append(item)


@dataclass
class OrderReadModel:
    …
14 0 Open
System design patterns easy

How to Implement a Data Helper Class in Python

Build a beginner-friendly DataHelper class using dataclasses and key system design patterns like Command, Strategy, and Map.

dataclass data-helper design-patterns
Python
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional


@dataclass
class DataHelper:
    """A beginner-friendly data utility with common system design patterns."""
    data: List[Dict[str, Any]] = field(default_factory=list)

    def add_record(self, r…
13 0 Open
System design patterns easy

How to Implement a Factory Method by Type String in Python

A factory method maps a type string to a class, creating and returning the appropriate object instance while handling unknown types gracefully.

factory-pattern design-patterns oop
Python
class Animal:
    def speak(self):
        raise NotImplementedError


class Dog(Animal):
    def speak(self):
        return "Woof!"


class Cat(Animal):
    def speak(self):
        return "Meow!"


class AnimalFactory:
    @staticmethod
    def create(animal_type: str) -> Animal:
        animal_types = {
          …
14 0 Open
System design patterns easy

How to Implement a Simple Event Bus in Python

Create a publish-subscribe event bus using dataclasses and defaultdict to decouple event producers from consumers.

event-bus publish-subscribe design-patterns
Python
from collections import defaultdict
from dataclasses import dataclass, field
from typing import Callable, Dict, List, Set


@dataclass
class EventBus:
    _subscribers: Dict[str, List[Callable]] = field(
        default_factory=lambda: defaultdict(list)
    )

    def subscribe(self, event_type: str, handler: Callable…
15 0 Open
System design patterns medium

How to Implement a Simple MVVM Binding Mock in Python

A minimal Python implementation of the MVVM pattern, mocking data binding so views auto-update when the view model changes.

mvvm binding observer pattern
Python
class BindingMock:
    def __init__(self, view_model):
        self.view_model = view_model
        self.subscribers = []

    def bind(self, property_name, callback):
        self.subscribers.append((property_name, callback))

    def set(self, property_name, value):
        setattr(self.view_model, property_name, va…
18 0 Open
System design patterns medium

How to Implement the Abstract Factory Pattern in Python

Implements the Abstract Factory pattern to create families of related GUI objects (buttons, checkboxes) without specifying their concrete classes.

abstract-factory design-patterns system-design
Python
from abc import ABC, abstractmethod


class Button(ABC):
    @abstractmethod
    def render(self):
        pass


class Checkbox(ABC):
    @abstractmethod
    def render(self):
        pass


class WindowsButton(Button):
    def render(self):
        return "Rendering Windows-style button"


class WindowsCheckbox(Chec…
13 0 Open
System design patterns medium

How to Implement the Flyweight Pattern in Python

Implements the Flyweight design pattern to share immutable intrinsic state (character + font) across many document objects, reducing memory usage.

flyweight design-patterns memory-optimization
Python
class Character:
    """Flyweight - stores only intrinsic state (shared)."""

    def __init__(self, char: str, font: str):
        self.char = char
        self.font = font

    def render(self, size: int) -> str:
        return f"{self.char}_{self.font}_{size}"


class CharacterFactory:
    """Flyweight factory - ma…
15 0 Open
System design patterns easy

How to Implement the Prototype Pattern with Deep Copy in Python

Implements the Prototype design pattern using copy.deepcopy to clone complex objects without sharing mutable state.

prototype-pattern deepcopy dataclasses
Python
import copy
from dataclasses import dataclass, field
from typing import List

@dataclass
class Engine:
    horsepower: int

@dataclass
class Car:
    brand: str
    engine: Engine
    accessories: List[str] = field(default_factory=list)

def clone_prototype(car: Car) -> Car:
    return copy.deepcopy(car)

if __name__ …
13 0 Open
System design patterns easy

How to Implement the Repository Pattern in Python with an In-Memory Dict

Stores, retrieves, updates, and deletes user records in memory using a Repository abstraction over a plain dict, isolating data access from business logic.

repository-pattern design-patterns in-memory
Python
class UserRepository:
    def __init__(self):
        self._storage = {}
        self._next_id = 1

    def create(self, name, email):
        user_id = self._next_id
        self._next_id += 1
        self._storage[user_id] = {"id": user_id, "name": name, "email": email}
        return self._storage[user_id]

    def…
11 0 Open
System design patterns medium

How to Migrate a Legacy Facade with the Strangler Fig Pattern in Python

Use a facade to wrap a legacy API and incrementally migrate callers to a modern interface, following the strangler fig pattern.

facade legacy migration
Python
class LegacyAPI:
    """Simulates the legacy system's raw interface."""
    def get_user(self, user_id):
        return {"id": user_id, "name": "Alice", "legacy": True}


class UserService:
    """Facade that wraps the legacy system with a modern interface."""
    def __init__(self, legacy_api=None):
        self.lega…
12 0 Open
System design patterns medium

Lazy loading with a proxy in Python: defer expensive service creation

A lazy proxy defers creating an expensive service object until its method is first called, then caches it for reuse.

proxy lazy-loading design-patterns
Python
import time
import random


class ExpensiveService:
    def __init__(self, name):
        self.name = name
        print(f"Creating expensive service: {self.name}")

    def fetch_data(self):
        time.sleep(1)
        return f"Data from {self.name}: {random.randint(1, 100)}"


class LazyProxy:
    def __init__(sel…
15 0 Open
System design patterns medium

Microkernel Plug-in Core Mock in Python

Implements a minimal microkernel plug-in core that registers, unregisters, and executes synchronous or asynchronous plugins via a pluggable manager class.

microkernel plugin design-patterns
Python
import json
import abc
import inspect


class MicrokernelCore(abc.ABC):

    def __init__(self):
        self._plugins = {}

    def register(self, name, plugin):
        self._plugins[name] = plugin

    def unregister(self, name):
        return self._plugins.pop(name, None)

    def execute(self, name, *args, **kwa…
13 0 Open
System design patterns medium

Object Pool Pattern for Database Connections in Python

Implements a reusable connection pool with acquire/release and context manager support, mocking database connections with idle reuse and exhaustion handling.

object-pool connection-pool databases
Python
import time
from contextlib import contextmanager
from collections import deque


class ConnectionPool:
    def __init__(self, size=3, max_idle=5):
        self._idle = deque(maxlen=max_idle)
        self._active = set()
        self.size = size

    def _create(self):
        return {"created_at": time.time(), "queri…
12 0 Open
System design patterns medium

Singleton Config Loader in Python with Caution

Implements a singleton config loader in Python that reads JSON config files, but demonstrates the hidden gotcha of shared state across instances.

singleton config design-patterns
Python
import json
from pathlib import Path

class ConfigLoader:
    _instance = None

    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self, config_file="config.json"):
        if not hasattr(self, "loaded…
12 0 Open
System design patterns medium

Template Method Workflow Steps Base Class in Python

Define a reusable workflow skeleton in a base class and let subclasses fill in each step with the Template Method design pattern.

template-method design-patterns abc
Python
from abc import ABC, abstractmethod


class DataPipeline(ABC):
    """Template Method pattern: defines a workflow skeleton."""

    def run(self):
        """Template method - defines the algorithm's structure."""
        result = {"extracted": False, "transformed": False, "loaded": False}
        raw_data = self._ext…
13 0 Open
API design & gRPC easy

How to Build a Simple Filter Helper in Python for API Design

Create a reusable data filter service with dataclasses that mimics gRPC request/response patterns for filtering dataset records.

filtering dataclasses grpc
Python
from dataclasses import dataclass, field
from typing import List, Optional, Dict, Any


@dataclass
class FilterRequest:
    """A simple filter request mirroring a gRPC message structure."""
    field_name: str
    operator: str  # eq, ne, gt, lt, contains
    value: Any
    page_size: int = 10
    page_token: Optional…
13 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 medium

Kafka Consumer Poll Loop Mock in Python

Simulate a Kafka consumer poll loop with a mock class, process messages in batches, and commit offsets to understand streaming consumption patterns.

kafka streaming mock
Python
import time

class MockKafkaConsumer:
    def __init__(self, topic, messages):
        self.topic = topic
        self.messages = list(messages)
        self.position = 0

    def poll(self, timeout_ms=100):
        if self.position >= len(self.messages):
            time.sleep(timeout_ms / 1000)
            return []…
13 0 Open
Observability & SRE medium

How to Track Cache Hit Ratio in Python

Simulate an LRU cache with hit/miss tracking and compute a real-time hit ratio from random access patterns.

cache lru hit-ratio
Python
import random
import time
from collections import OrderedDict

class LRUCache:
    def __init__(self, capacity: int):
        self.cache = OrderedDict()
        self.capacity = capacity
        self.hits = 0
        self.misses = 0

    def get(self, key):
        if key in self.cache:
            self.hits += 1
     …
13 0 Open
Microservices patterns medium

CQRS with Separate Read and Write Repositories in Python

Implement CQRS in Python with separate write and read repositories, using commands for mutations and frozen DTOs for queries.

cqrs repositories microservices
Python
from dataclasses import dataclass
from typing import Dict, List, Optional


# --- Write side: commands mutate state ---
@dataclass
class CreateUserCommand:
    id: int
    name: str


class UserWriteRepository:
    def __init__(self) -> None:
        self._store: Dict[int, Dict[str, object]] = {}

    def create(self,…
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.