Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
How to Create a Data Helper Class in Python with OOP
A complete OOP example with User, Post, and Blog classes that manage data relationships and provide clear helper methods.
class User:
def __init__(self, name, email):
self.name = name
self.email = email
self.posts = []
def create_post(self, title, content):
post = Post(title, content, self)
self.posts.append(post)
return post
def get_post_count(self):
return len(self.p…
How to Build a System-User-Assistant Message List in Python
Use dataclasses to model a chat conversation and build the system/user/assistant message list expected by LLM APIs.
from dataclasses import dataclass, field
from typing import List
@dataclass
class Message:
role: str
content: str
@dataclass
class Conversation:
messages: List[Message] = field(default_factory=list)
def add_system(self, content: str) -> None:
self.messages.append(Message(role="system", con…
How to Parse Chat Completion JSON in Python
Parse a mock OpenAI chat completion JSON response into a clean dictionary with content, finish reason, and model.
import json
def parse_chat_response(raw: str) -> dict:
data = json.loads(raw)
choice = data["choices"][0]
return {
"content": choice["message"]["content"],
"finish_reason": choice["finish_reason"],
"model": data["model"],
}
if __name__ == "__main__":
mock_response = '''
…
How to Parse JSON from LLM Model Output Fence in Python
Extract and parse a JSON object from a language model's output that may be wrapped in triple-backtick fences with an optional language tag.
import json
import re
def parse_json_from_fence(text):
"""
Extract JSON object from a model output that may be wrapped in
triple-backtick fences with optional language tag.
"""
# Match content inside
How to Mock a Whisper API Transcription Stub in Python
Simulate an OpenAI Whisper-style transcription response with a dataclass request model and a mock function that returns structured audio transcription output.
import json
from dataclasses import dataclass
from typing import Optional
@dataclass
class AudioRequest:
file_path: str
language: Optional[str] = None
def to_api_payload(self) -> dict:
return {"file": self.file_path, "language": self.language}
def mock_whisper_transcribe(payload: dict) -> dict:
…
Resize Disk Partitions in Python (Mock Script)
A mock disk partition resize script that uses dataclasses to model partitions, validate new sizes, and output the updated layout as JSON.
#!/usr/bin/env python3
"""Mock script to demonstrate disk partition resize logic."""
import json
from dataclasses import dataclass
from typing import Dict
@dataclass
class Partition:
name: str
size_gb: int
mount_point: str
def to_dict(self) -> Dict[str, object]:
return {
"name": …
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
…
Python MVC Pattern Example (Model-View-Controller)
A minimal, runnable Model-View-Controller (MVC) example in pure Python that separates data, presentation, and logic.
class Model:
def __init__(self):
self.data = {"title": "Initial Title", "content": "Initial Content"}
def get_data(self):
return self.data
def update_data(self, title=None, content=None):
if title:
self.data["title"] = title
if content:
self.data["c…
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…
Modeling a Hive Metastore Table Schema in Python
A dataclass that mimics a Hive metastore table schema—columns, partition keys, storage format, and location—with helper methods for description and mutation.
from dataclasses import dataclass, field
from typing import Dict, List, Optional
@dataclass
class HiveTable:
"""Simple mock of a Hive metastore table schema."""
name: str
database: str = "default"
columns: List[Dict[str, str]] = field(default_factory=list)
partition_keys: List[Dict[str, str]] = f…
Champion Challenger Deployment Mock in Python
Simulates an A/B champion-challenger ML deployment workflow — comparing two mock model accuracies and deciding which to promote to production.
import random
import time
class ModelMocker:
def __init__(self, name="Model", accuracy=0.85):
self.name = name
self.accuracy = accuracy
def predict(self, data):
"""Simulate prediction with some randomness."""
time.sleep(0.005) # simulate compute time
return 1 if rando…
Compare Model A vs Model B Metrics in Python
A script that simulates and compares metrics between two ML models, showing a formatted diff table for quick insight.
import random
def compare_a_b(samples=5):
"""Mock comparison of model A vs model B predictions."""
metrics = ["accuracy", "precision", "recall", "f1"]
print(f"{'Metric':<12}{'Model A':>10}{'Model B':>10}{'Diff':>10}")
print("-" * 42)
random.seed(42)
for metric in metrics:
a = round(r…
How to Evaluate Accuracy, Precision, and Recall in Python
Compute accuracy, precision, and recall for a binary classification model using scikit-learn's metrics functions.
from sklearn.metrics import accuracy_score, precision_score, recall_score
if __name__ == "__main__":
y_true = [0, 1, 1, 0, 1, 0, 1, 1]
y_pred = [0, 1, 0, 0, 1, 0, 1, 1]
accuracy = accuracy_score(y_true, y_pred)
precision = precision_score(y_true, y_pred)
recall = recall_score(y_true, y_pred)
…
How to Mock Shadow Mode Inference in Python
Simulates running multiple candidate models in shadow mode by adding randomized delays and returning their outputs alongside a primary model's output.
import random
import time
def shadow_mode_inference(candidates, mock_delay=0.1):
"""
Simulates running multiple candidate models in 'shadow mode'
by adding tiny randomized delays and returning their outputs
alongside the primary model's output.
"""
primary_output = "primary: answer"
shado…
How to Run Batch Predictions with a Mock Model in Python
Build a lightweight mock model class and run predictions across a batch of samples, returning results as a plain Python list.
import numpy as np
class MockModel:
def __init__(self, weights):
self.weights = np.array(weights)
def predict(self, X):
return X @ self.weights
def predict_batch(model, batch):
"""Run predictions for a batch of samples and return results as a list."""
return model.predict(np.array(ba…
How to Save and Load PyTorch Model State Dict in Python
This code demonstrates how to save a PyTorch model's state dict to a file and load it back into a new model instance, verifying weights match.
import torch
import torch.nn as nn
class SimpleNet(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(4, 8)
self.fc2 = nn.Linear(8, 2)
def forward(self, x):
x = torch.relu(self.fc1(x))
return self.fc2(x)
if __name__ == "__main__":
model = Simp…
How to Save and Load a Mock Model with Pickle and joblib in Python
Serialize a custom machine learning model to a .joblib file with joblib.dump, reload it, and run a prediction with joblib.load.
import joblib
from pathlib import Path
class MockModel:
def __init__(self, weights):
self.weights = weights
def predict(self, features):
return sum(w * f for w, f in zip(self.weights, features))
def save_model_pickle(model, filepath):
with open(filepath, "wb") as f:
joblib.dump(…
How to Trigger Model Retraining on Drift in Python
Automatically detects accuracy drift in a mock ML model and triggers retraining when performance falls below a threshold.
import random
import time
class MockModel:
def __init__(self, name):
self.name = name
self.accuracy = 0.85
self.version = 1
def train(self, data_size):
# Simulate training time and accuracy improvement
time.sleep(0.1)
drift = random.uniform(-0.02, 0.02)
…
How to do feature selection with VarianceThreshold in Python
This code demonstrates how to use scikit-learn's VarianceThreshold to remove low-variance features from a NumPy array, keeping only those that vary enough to be useful for modeling.
import numpy as np
from sklearn.feature_selection import VarianceThreshold
def main():
# Mock dataset: 4 samples, 5 features
X = np.array([
[0.1, 0.2, 1.0, 1.0, 0.5],
[0.2, 0.2, 0.0, 1.0, 0.4],
[0.1, 0.2, 1.0, 1.0, 0.6],
[0.3, 0.2, 1.0, 0.0, 0.5]
])
# Select features w…
How to implement a canary traffic split in Python
Route incoming traffic between stable and canary model or service versions using a weight-based random split with deterministic testing.
import random
def canary_route(service_name: str, canary_weight: float = 0.2) -> str:
"""Route traffic between stable and canary versions based on weight."""
rng = random.Random(42) # deterministic for reproducible demo
if rng.random() < canary_weight:
return f"{service_name}-canary"
return …
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.
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…
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.