Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
How to Mock a Failing Dependency to Test Error Paths in Python
Inject a fake HTTP client that raises a connection error to test how code handles dependency failures without touching the network.
import requests
def fetch_user(user_id):
url = f"https://api.example.com/users/{user_id}"
response = requests.get(url, timeout=5)
response.raise_for_status()
return response.json()
def get_user_name(user_id, http_client):
try:
user_data = http_client(user_id)
return user_data["nam…
Generate UUID4 Values with a Python Generator
This code defines a generator function that yields mock UUID4 values, allowing you to stream unique identifiers one at a time.
import uuid
def generate_uuids(count=5):
"""Generate a stream of mock UUID4 values."""
for _ in range(count):
yield uuid.uuid4()
if __name__ == "__main__":
# Generate and print 5 UUIDs
for uid in generate_uuids(5):
print(uid)
How to Batch Embed a List of Strings in Python
Batch embed a list of strings into deterministic pseudo-random vectors using a mock encoder class.
class MockEncoder:
def __init__(self, dim=8, seed=42):
self.dim = dim
self.seed = seed
def embed(self, text):
# Deterministic pseudo-random embedding based on text content
hash_val = hash(text)
import random
rng = random.Random(hash_val + self.seed)
retu…
How to Build a Simple Semantic Cache for Similar Prompts in Python
Mock a semantic cache that finds the closest matching prompt using word-overlap similarity and returns cached results above a threshold.
prompt_cache = [
"What is the capital of France?",
"How does recursion work?",
"Best practices for Python logging?",
"Explain binary search in one line.",
"How to reverse a string in Python?"
]
def normalize(text):
return " ".join(text.lower().split())
def similarity(a, b):
a_words = set(…
How to Compute a Mock BLEU Score with n-gram Overlap in Python
Evaluate text similarity with a simplified BLEU score using word-level n-gram precision and a brevity penalty.
from collections import Counter
def bleu_score(reference, candidate, n=2):
"""
Compute a simplified BLEU score with n-gram precision and brevity penalty.
Mock demo using word-level n-grams.
"""
ref_tokens = reference.lower().split()
cand_tokens = candidate.lower().split()
# Compute n-…
How to Create a Mock LLM Judge Rubric Score in Python
Scores a response against a rubric by counting keyword matches, returning total, percentage, and per-criterion feedback.
def judge_score(response, rubric):
"""Mock LLM judge that scores a response against a rubric."""
total = 0
max_total = 0
feedback = []
for criterion, rubric_item in rubric.items():
max_points = rubric_item["max"]
description = rubric_item["description"]
# Simple mock scori…
How to Create a Mock Text Embedding with Hash in Python
Generate deterministic mock text embeddings using SHA-256 hashing and numpy, producing normalized vectors for similarity testing without an LLM.
import hashlib
import numpy as np
def mock_embed(text: str, dim: int = 10, seed: int = 42) -> np.ndarray:
"""Generate a deterministic mock embedding using a hash function.
Args:
text: Input text to embed
dim: Dimension of the output vector
seed: Seed for reproducibility
R…
How to Mock OpenAI Tool Call Messages in Python
Create an assistant message with a function tool call in OpenAI's chat format, useful for testing and mocking.
from openai import OpenAI
def mock_tool_call(tool_name: str, arguments: dict) -> dict:
"""Simulate a tool call message in OpenAI style."""
return {
"role": "assistant",
"content": None,
"tool_calls": [
{
"id": "call_" + "a1b2c3d4e5f6",
"type…
How to Mock an LLM Client in Python
Create a simple mock LLM client that returns a canned completion for testing or development without a real API.
from dataclasses import dataclass
@dataclass
class MockLLMClient:
canned_response: str = "This is a canned completion."
def complete(self, prompt: str) -> str:
return f"{self.canned_response} [to: {prompt[:20]}]"
if __name__ == "__main__":
client = MockLLMClient()
result = client.complete(…
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 Stream Tokens from a Mock LLM in Python
Simulate real-time LLM streaming by yielding tokens one at a time with a delay, making it easy to test streaming UIs.
import time
from typing import Generator
def stream_tokens(text: str, delay: float = 0.05) -> Generator[str, None, None]:
"""Simulate an LLM streaming tokens word by word."""
for word in text.split():
yield word
time.sleep(delay)
if __name__ == "__main__":
sample = "Hello world! This is…
How to build a mock RAG pipeline in Python
Build a minimal Retrieval-Augmented Generation pipeline that retrieves the best-matching document by keyword overlap and generates a template-based answer.
def simple_rag_pipeline(question, documents):
"""
A minimal mock RAG pipeline: retrieve relevant context, then generate an answer.
"""
# Step 1: Retrieve — mock retrieval by simple keyword scoring
scores = []
for doc in documents:
doc_words = set(doc.lower().split())
question_wo…
Automate Tweeting New Blog Posts in Python
A mock script that fetches new blog posts from a CMS and tweets them via a simulated Twitter API, outputting JSON results.
import json
import time
from datetime import datetime
def fetch_new_blog_posts():
"""Mock function to simulate fetching latest blog posts from a CMS."""
return [
{
"id": 1,
"title": "Getting Started with Python",
"url": "https://blog.example.com/python-start",
…
Create Mock Watermarked Image Bytes in Python Without PIL
Builds a mock image-like byte stream with an embedded watermark using only stdlib modules, for testing pipelines without PIL.
from io import BytesIO
import zlib
import struct
def create_watermarked_bytes(width: int, height: int, watermark: bytes) -> bytes:
"""Create a mock image-like byte stream with a watermark (no PIL)."""
header = struct.pack("<2I", width, height)
payload = watermark * max(1, (width * height // max(1, len(wa…
Fetch weather API mock and write dashboard HTML in Python
This script fetches a mock weather API response as a Python dict, builds a simple HTML dashboard, writes it to a file, and prints both the file path and JSON payload.
from datetime import datetime
import json
import os
def fetch_weather_mock(city: str) -> dict:
"""Return a mock weather payload for a given city."""
return {
"city": city,
"temperature_c": 21.5,
"condition": "Partly Cloudy",
"humidity": 58,
"wind_kph": 12.3,
"u…
Fill PDF Form Fields from a Mock Template in Python
Fills a PDF-style form template dictionary with user data, preserving template fields and formatting output as JSON.
import json
template = {
"first_name": "",
"last_name": "",
"email": "",
"phone": "",
"date_of_birth": "",
"address": "",
"city": "",
"state": "",
"zip_code": "",
"agree_to_terms": False
}
def fill_pdf_form(template: dict, data: dict) -> dict:
for key, value in data.items…
How to Create a Mock Headless Browser Screenshot Stub in Python
This code provides a deterministic stub that simulates capturing webpage screenshots with a headless browser, returning formatted output without real browser dependencies.
import subprocess
import sys
def mock_screenshot_webpage(url: str, width: int = 1280, height: int = 800) -> str:
"""Stub that simulates taking a screenshot of a webpage using headless browser."""
# In real implementation, you would use playwright/selenium/headless chrome
result = {
"url": url,
…
How to Cross Post Markdown to dev.to API in Python
A Python function that POSTs markdown content to the dev.to API and handles HTTP or URLError exceptions with mock API testing.
import json
from urllib import request, error
def cross_post_to_devto(markdown_content, api_key, devto_api_url="https://dev.to/api/articles"):
"""
Mock cross-posting of markdown content to the dev.to API.
Returns the API response or an error message.
"""
payload = json.dumps({
"article": …
How to Generate a cloud-init User Data Mock in Python
Generate a cloud-init user data mock for a VM using a dataclass and JSON in Python.
import json
from dataclasses import dataclass, asdict
@dataclass
class VMConfig:
hostname: str
cpus: int
memory_mb: int
ssh_key: str
def generate_cloud_init_mock(config: VMConfig) -> str:
"""Build a cloud-init user-data mock for a VM."""
user_data = {
"hostname": config.hostname,
…
How to Map Network Drive Paths to Local Paths in Python
Convert mock SMB network drive paths (like 'S:\reports\q1.xlsx') to local placeholder paths and back using a simple mapping dictionary in Python.
"""Map mock SMB network drive paths to local placeholder paths."""
from dataclasses import dataclass
@dataclass(frozen=True)
class NetworkDrive:
letter: str
remote_path: str
DRIVES = {
"S:": NetworkDrive("S", r"\\server01\shares\sales"),
"M:": NetworkDrive("M", r"\\server02\media\movies"),
"X:": …
How to Merge PDFs in Python (Mock pypdf Stub)
Merge PDF files by concatenating their raw byte content using a simple stubbed class that mimics the pypdf interface.
import io
from hashlib import sha256
class PdfStub:
def __init__(self, data: bytes, name: str):
self.data = data
self.name = name
def get_content_bytes(self) -> bytes:
return self.data
def merge_pdfs_mock(pdf_stubs) -> bytes:
merged = io.BytesIO()
for stub in pdf_stubs:
…
How to Mock FFmpeg subprocess Calls in Python
Compress a video with ffmpeg while mocking subprocess.run to test the command construction without executing the actual encoder.
import subprocess
from unittest.mock import Mock, patch
def compress_video(input_path: str, output_path: str, crf: int = 23) -> None:
"""Compress a video using ffmpeg with a given CRF (quality) value."""
command = [
"ffmpeg",
"-i", input_path,
"-c:v", "libx264",
"-crf", str(cr…
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:
…
How to Mock an Ansible Inventory in Python
Load an Ansible-style inventory JSON file into Python and simulate a playbook run across hosts and groups.
import json
from pathlib import Path
class InventoryMock:
def __init__(self, inventory_file: str):
self.inventory_file = Path(inventory_file)
self.hosts = {}
def load(self):
if not self.inventory_file.exists():
raise FileNotFoundError(f"Inventory file {self.inventory_file…
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.