Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
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.
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…
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.
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
…
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.
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:
…
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.
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…
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.
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…
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.
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__ …
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.
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,…
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.
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…
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.
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…
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.
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…
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.
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…
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.
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."""
…
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.
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…
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.
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))
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.
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…
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.
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…
Event Envelope with Schema Version Field in Python
Build a typed event envelope dataclass with an explicit schema version field for mock streaming scenarios.
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…
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.
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…
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.
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,…
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.
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…
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.
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…
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.
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…
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.
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…
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.
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)
…
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
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- 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.