Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
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…
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…
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 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…
Export Metrics with OTLP Mock in Python
Simulates system metric collection and exports them as an OTLP-like JSON payload using only Python's standard library.
from dataclasses import dataclass, asdict
import json
import random
import time
@dataclass
class Metric:
name: str
value: float
timestamp: int
unit: str = "1"
def collect_system_metrics() -> list[Metric]:
"""Mock metric collection for OTLP export simulation."""
now = int(time.time())
re…
How to Add Metadata Attributes to a Span in Python
Create a lightweight dataclass-based Span mock that stores key-value metadata attributes for tracing or event logging.
from dataclasses import dataclass, field
from typing import Dict, Any
@dataclass
class Span:
name: str
attributes: Dict[str, Any] = field(default_factory=dict)
def set_attribute(self, key: str, value: Any) -> None:
self.attributes[key] = value
def get_attribute(self, key: str) -> Any…
How to Model Span Events in Python
Define a Span class with timestamped milestone events and a completion marker to track operation lifecycle.
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import List
class SpanStatus(Enum):
STARTED = "started"
COMPLETED = "completed"
@dataclass
class SpanEvent:
name: str
timestamp: float = field(default_factory=time.time)
attributes: dict = field(default_facto…
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.
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,…
How to Implement a Data Helper for Microservices in Python
Create a reusable helper class to serialize, deserialize, and wrap data for microservice communication using dataclasses and JSON.
import json
from dataclasses import dataclass, asdict
from typing import Any, Dict, List
@dataclass
class ServiceResponse:
status: str
data: Any
message: str = ""
class DataHelper:
"""Simple helper for microservice data handling."""
@staticmethod
def serialize(data: Dict[str, Any]) -> str:…
How to Mock a Choreography Saga in Python
Simulate a choreography-based saga with event envelopes, status tracking, and compensating actions to model distributed transactions.
import json
from dataclasses import dataclass, asdict
from typing import List, Optional
from enum import Enum
class SagaStatus(Enum):
PENDING = "PENDING"
COMPLETING = "COMPLETING"
COMPLETED = "COMPLETED"
FAILED = "FAILED"
@dataclass
class EventEnvelope:
event_type: str
order_id: str
sta…
How to Mock a GraphQL Backend in Python
Create an in-memory GraphQL mock backend using dataclasses and resolver methods returning plain dictionaries.
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…
How to implement the Database per service pattern in Python
Simulate separate databases per microservice in Python using dataclasses and in-memory dictionaries, showing how services own their data independently.
import json
from dataclasses import dataclass, asdict
from typing import Dict, List
@dataclass
class User:
id: int
name: str
email: str
@dataclass
class Order:
id: int
user_id: int
product: str
amount: float
class UserServiceDB:
"""Simulates a separate database for the User servic…
How to Build a Data Validation Schema in Python
Create a lightweight validation schema using dataclasses and lambda validators to check fields in a dictionary.
import re
from dataclasses import dataclass, field
from typing import Any, Callable
@dataclass
class Field:
name: str
validator: Callable[[Any], bool]
required: bool = True
def validate(self, value: Any) -> bool:
if not self.required and value is None:
return True
return …
How to Mock a Kubeflow Pipeline in Python
Build a minimal in-memory mock of a Kubeflow pipeline DAG using dataclasses and OrderedDict to chain component functions.
from typing import Dict, Any
from dataclasses import dataclass, field
from collections import OrderedDict
@dataclass
class KubeflowPipelineMock:
"""A minimal mock of a Kubeflow pipeline DAG."""
name: str
components: OrderedDict[str, callable] = field(default_factory=OrderedDict)
def add_component(se…
Mock a Flyte ML workflow in Python
Build a lightweight mock of a Flyte ML pipeline with dataclasses and a simple execution loop that passes outputs between tasks.
from dataclasses import dataclass, field
from typing import List, Dict, Optional
import time
@dataclass
class FlyteTask:
name: str
inputs: Dict = field(default_factory=dict)
outputs: Dict = field(default_factory=dict)
def run(self) -> Dict:
time.sleep(0.1) # simulate work
return sel…
Cross Shard Query Scatter Gather Mock in Python
Simulate a distributed database cross-shard query using a scatter-gather pattern with a mock Python implementation.
from dataclasses import dataclass
from typing import List, Dict
@dataclass
class NodeResponse:
node_id: int
data: Dict[str, float]
def mock_query_shard(shard_id: int, shard_data: Dict[str, float], query: str) -> NodeResponse:
"""Simulate querying a single shard, returning matches whose value > 50."""
…
How to Replicate Data Across All Shards in Python
Mocks a global table that replicates a key-value pair to every shard, ensuring reads return the same value from any shard.
from dataclasses import dataclass
from typing import Dict, List
@dataclass
class Shard:
id: str
data: Dict[str, int]
class GlobalTable:
def __init__(self, shards: List[Shard]):
self._shards = {s.id: s for s in shards}
def set_value(self, key: str, value: int) -> None:
"""Replicate …
How to Build a GitOps Argo CD Sync Mock in Python
Simulate Argo CD-style GitOps deployment sync with Python dataclasses, random success rates, and force-sync retry logic.
import random
import time
from dataclasses import dataclass, field
from typing import List, Dict
@dataclass
class Application:
name: str
source_repo: str
target_revision: str
synced: bool = False
health_status: str = "Healthy"
history: List[Dict] = field(default_factory=list)
def sync(se…
How to Mock a CI Pipeline with Build, Test, and Deploy Stages in Python
Simulate a three-stage CI pipeline (build, test, deploy) in Python with random pass/fail logic, early exit on failure, and measured stage durations.
import time
import random
from dataclasses import dataclass
@dataclass
class StageResult:
name: str
status: str
duration: float
def run_stage(name: str, success_chance: float = 0.9) -> StageResult:
"""Simulate a pipeline stage with random success/failure."""
start = time.time()
time.sleep(r…
How to Mock a Dockerfile Multi-Stage Build in Python
Simulate a Dockerfile multi-stage build process in Python using dataclasses to validate stage ordering and file availability before you write the real Dockerfile.
from dataclasses import dataclass
from pathlib import Path
@dataclass
class BuildStage:
name: str
base_image: str
files: list[str]
commands: list[str]
def run_build(stage: BuildStage, context_dir: Path):
print(f"=== Stage: {stage.name} (base: {stage.base_image}) ===")
for file in stage.file…
How to Mock a Feature Flag Rollout Percentage in Python
Simulate a percentage-based feature flag rollout by hashing a user ID to deterministically enable features for a subset of users.
import random
from dataclasses import dataclass
@dataclass
class FeatureFlag:
name: str
rollout_percentage: int
def is_feature_enabled(feature_flag: FeatureFlag, user_id: str) -> bool:
hashed_id = hash(user_id) % 100
return hashed_id < feature_flag.rollout_percentage
if __name__ == "__main__":
…
How to Mock a GitHub Actions Workflow in Python
Build a dataclass-based model of a GitHub Actions workflow and simulate its execution to validate steps and outputs before deployment.
import json
from dataclasses import dataclass, asdict
from typing import List, Dict, Any
@dataclass
class Step:
name: str
run: str
@dataclass
class Job:
name: str
steps: List[Step]
runs_on: str = "ubuntu-latest"
@dataclass
class Workflow:
name: str
jobs: List[Job]
def to_github_a…
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.