Reference library

Python Code Samples

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

83 matches
Testing & modern typing easy

How to Validate Dataclass Fields with Python Type Hints

A beginner-friendly helper that checks if instance attributes match their declared type hints using dataclasses and get_type_hints.

dataclasses type-hints validation
Python
from typing import Any, TypeVar, get_type_hints
from dataclasses import dataclass

T = TypeVar("T")

@dataclass
class User:
    name: str
    age: int
    email: str

def validate_fields(obj: Any) -> dict[str, bool]:
    """Check if object attributes match declared type hints."""
    hints = get_type_hints(obj.__class…
13 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 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 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 medium

Inbox pattern consumer dedupe mock in Python

Implements a mock inbox consumer that deduplicates incoming messages by ID, with automatic eviction of old seen IDs to prevent unbounded memory growth.

deduplication inbox-pattern dataclasses
Python
import json
from collections import deque
from dataclasses import dataclass, field
from hashlib import sha256
from typing import Any


@dataclass
class InboxConsumer:
    max_seen: int = 1000
    seen_ids: set = field(default_factory=set)
    seen_history: deque = field(default_factory=deque)

    def _mark_seen(self,…
13 0 Open
API design & gRPC easy

Create a Data Helper in Python for gRPC-style APIs

This code builds a simple DataHelper class that mimics gRPC request/response handling with in-memory storage, JSON serialization, and basic CRUD operations for beginners.

dataclasses grpc api-design
Python
import json
from dataclasses import dataclass, asdict
from typing import Dict, Any


@dataclass
class User:
    user_id: int
    name: str
    email: str


class DataHelper:
    """Simple helper to demonstrate gRPC-like data handling for beginners."""

    def __init__(self) -> None:
        self._users: Dict[int, Use…
14 0 Open
API design & gRPC easy

Format data in Python using dataclasses like gRPC messages

Convert Python dataclasses to and from dicts and format them gRPC-style for clean data handling.

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


@dataclass
class ProductInfo:
    """Data class representing a gRPC-style product message."""

    name: str
    price: float
    tags: List[str]
    description: Optional[str] = None

    def to_dict(self) -> Dict[str, Any]:
        """C…
14 0 Open
API design & gRPC easy

How to Build a Data Helper Class in Python for Beginners

Create a beginner-friendly DataHelper class that stores, retrieves, filters, and summarizes records in a list of dictionaries.

dataclasses data-handling beginner
Python
from __future__ import annotations

import json
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional


@dataclass
class DataHelper:
    """A beginner-friendly helper for common data tasks."""

    data: List[Dict[str, Any]] = field(default_factory=list)

    def add_record(self, record…
14 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
API design & gRPC easy

How to Build a Simple gRPC-Style Data Service in Python

Create a beginner-friendly gRPC-style service with dataclasses to simulate GetUser and CreateUser RPCs.

grpc dataclasses api-design
Python
from dataclasses import dataclass
from typing import Optional


@dataclass
class User:
    id: int
    name: str
    email: str


class UserService:
    """Simple gRPC-style service contract for beginner learners."""

    def get_user(self, user_id: int) -> Optional[User]:
        """Simulated gRPC GetUser RPC."""
   …
13 0 Open
API design & gRPC easy

How to Implement Sparse Fieldsets in Python

A function that filters API responses by resource type, returning only requested fields plus IDs, as a sparse fieldset mock.

api jsonapi sparse-fieldsets
Python
from dataclasses import dataclass, field
from typing import Dict, List, Optional


@dataclass
class MockResponse:
    data: Dict[str, object] = field(default_factory=dict)
    included: List[Dict[str, object]] = field(default_factory=list)


def select_fields(
    data: Dict[str, object],
    sparse_fields: Optional[D…
12 0 Open
API design & gRPC easy

How to Serialize a Dataclass to JSON in Python

Serialize a Python dataclass instance to JSON using asdict and json.dumps for API responses or mocks.

dataclass json serialization
Python
from dataclasses import dataclass, asdict
import json


@dataclass
class UserResponse:
    id: int
    name: str
    email: str
    active: bool = True


if __name__ == "__main__":
    response = UserResponse(id=42, name="Ada Lovelace", email="ada@example.com")
    print(json.dumps(asdict(response), indent=2))
13 0 Open
API design & gRPC easy

Sort Python list by query param order_by

Sort a list of dataclass objects dynamically by a field name passed as a query param, with asc/desc direction support.

sorting dataclasses api
Python
from dataclasses import dataclass


@dataclass
class Item:
    name: str
    price: int


def sort_items(items, order_by, direction="asc"):
    if order_by not in ("name", "price"):
        raise ValueError(f"Unsupported sort field: {order_by}")

    reverse = direction.lower() == "desc"
    return sorted(items, key=l…
11 0 Open
Streaming & messaging easy

Build a Streaming Messaging Helper in Python

Create a simple message stream class that stores recent messages, sends user messages, and retrieves history or latest messages with timestamps.

streaming deque dataclass
Python
from collections import deque
from dataclasses import dataclass
from datetime import datetime
import time


@dataclass
class Message:
    user: str
    text: str
    timestamp: str = ""

    def __post_init__(self):
        if not self.timestamp:
            self.timestamp = datetime.now().strftime("%H:%M:%S")


class…
13 0 Open
Streaming & messaging easy

Event Envelope with Schema Version Field in Python

Build a typed event envelope dataclass with an explicit schema version field for mock streaming scenarios.

event dataclass messaging
Python
from dataclasses import dataclass, field
from datetime import datetime
import uuid


@dataclass
class Event:
    event_id: str = field(default_factory=lambda: str(uuid.uuid4()))
    event_type: str = "user.created"
    version: str = "1.0.0"
    created_at: str = field(default_factory=lambda: datetime.utcnow().isoform…
15 0 Open
Streaming & messaging easy

How to Build a Materialized View Updater Consumer Mock in Python

A mock consumer that queues change events and triggers refresh callbacks to simulate materialized view updates.

dataclasses deque mocking
Python
import time
from collections import deque
from dataclasses import dataclass, field
from typing import Callable, Deque, Optional


@dataclass
class MaterializedViewUpdater:
    """Mock updater that consumes change events and refreshes a view."""
    refresh: Optional[Callable[[str], None]] = None
    queue: Deque[tuple…
14 0 Open
Streaming & messaging easy

How to Implement a Priority Queue for Messages in Python

Build a message priority queue with heapq and dataclasses that pops messages by priority, using sequence numbers to keep insertion order.

priority-queue heapq dataclass
Python
import heapq
from dataclasses import dataclass, field
from typing import Any

@dataclass(order=True)
class Message:
    priority: int
    sequence: int = field(compare=False)
    content: str = field(compare=False)

class PriorityQueue:
    def __init__(self):
        self._heap = []

    def push(self, priority: int,…
15 0 Open
Streaming & messaging medium

How to Implement an Outbox Table Poll Publisher in Python

This code simulates an outbox pattern with a class that polls for pending records and publishes them as JSON messages, removing only those that are due.

outbox polling messaging
Python
import time
import json
from dataclasses import dataclass, asdict
from datetime import datetime, timedelta

@dataclass
class OutboxRecord:
    id: int
    topic: str
    payload: dict
    created_at: datetime

class OutboxPollPublisher:
    def __init__(self, poll_interval_seconds=1):
        self.poll_interval = poll…
11 0 Open
Streaming & messaging easy

How to Simulate a Micro-Batch Interval Trigger in Python

A dataclass-based mock that emits batch numbers at fixed intervals, mimicking a micro-batch streaming scheduler for testing and development.

streaming mock dataclass
Python
import time
from dataclasses import dataclass, field
from typing import List, Callable


@dataclass
class MicroBatchTriggerMock:
    batch_interval_seconds: float = 0.5
    max_batches: int = 5
    _batches_emitted: int = 0
    _next_emit_time: float = field(init=False, default=0)

    def start(self, on_batch: Callab…
13 0 Open
Streaming & messaging easy

How to Wrap Message Attributes in a CloudEvent with Python

Create a minimal CloudEvent dataclass that wraps arbitrary message attributes into a JSON envelope, matching CloudEvents 1.0 spec.

cloudevents messaging dataclasses
Python
import json
from dataclasses import dataclass, field, asdict
from typing import Any, Dict
from datetime import datetime, timezone


@dataclass
class CloudEvent:
    message_attributes: Dict[str, Any] = field(default_factory=dict)

    def wrap(self, event_id: str, source: str, event_type: str, data: Any):
        self…
13 0 Open
Streaming & messaging medium

How to mock a CQRS projector read model update in Python

Build a CQRS projector class that maintains denormalized read models by applying domain events in a mock order-processing service.

cqrs projector read-model
Python
from dataclasses import dataclass, field
from typing import Dict, List, Optional


@dataclass
class OrderReadModel:
    order_id: str
    customer_name: str
    total: float
    status: str = "pending"
    items: List[Dict] = field(default_factory=list)

    def apply_event(self, event_type: str, payload: Dict) -> Non…
11 0 Open
Streaming & messaging hard

Mock Protobuf Binary Encoding in Python

Demonstrates a minimal protobuf-like binary encoding and decoding of an event dataclass using varints and length-delimited fields in pure Python.

protobuf binary-encoding varint
Python
import struct
from dataclasses import dataclass


@dataclass
class Event:
    id: int
    user_id: int
    action: str

    def encode(self) -> bytes:
        # Mock protobuf-like binary encoding using varint and length-delimited fields
        buf = bytearray()
        # field 1: varint id (tag = (1 << 3) | 0 = 8)
  …
11 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.