Reference library

Python Code Samples

Easy snippets you can copy, study, and run in the browser editor.

157 matches
Errors & debugging easy

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.

testing mocking requests
Python
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…
16 0 Open
Errors & debugging easy

How to Test Exceptions in Python with pytest.raises

Learn the pytest.raises pattern to assert that specific exceptions are raised and validate their messages.

pytest testing exceptions
Python
import pytest


def divide(a: int, b: int) -> float:
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a / b


def test_divide_by_zero_raises():
    with pytest.raises(ValueError, match="Cannot divide by zero"):
        divide(10, 0)


def test_divide_by_zero_raises_exact_match():
    with py…
15 0 Open
AI & LLM integration patterns easy

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.

embeddings hashing numpy
Python
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…
13 0 Open
AI & LLM integration patterns easy

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.

openai tool-calls mock
Python
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…
14 0 Open
AI & LLM integration patterns easy

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.

llm mock testing
Python
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(…
16 0 Open
AI & LLM integration patterns easy

How to randomly assign a prompt variant to each key in Python

Randomly pick one variant from a list for each prompt key, useful for A/B testing message variations.

random dictionary a/b-testing
Python
import random

def assign_prompt_variant(prompts: dict[str, list[str]]) -> dict[str, str]:
    """Assign a random prompt variant to each prompt key."""
    return {key: random.choice(variants) for key, variants in prompts.items()}

if __name__ == "__main__":
    prompt_bank = {
        "greeting": ["Hello!", "Hi there…
14 0 Open
Automation & scripting easy

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.

watermark bytes zlib
Python
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…
13 0 Open
Automation & scripting easy

Generate Random Fake User Data for Testing in Python

This code generates a list of fake user dictionaries with random names, emails, ages, and timestamps using the Python standard library for testing purposes.

testing random data-generation
Python
import json
import random
import string
from datetime import datetime, timedelta

def generate_user_data(num_users=1):
    first_names = ["Alice", "Bob", "Charlie", "Diana", "Eve"]
    last_names = ["Smith", "Johnson", "Brown", "Taylor", "Wilson"]
    domains = ["example.com", "test.org", "demo.net"]
    
    users = …
38 0 Open
Automation & scripting easy

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.

api dev.to markdown
Python
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": …
10 0 Open
Automation & scripting easy

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.

subprocess mocking ffmpeg
Python
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…
13 0 Open
Automation & scripting easy

How to Mock subprocess Calls in Python with unittest.mock

A Python script that wraps Vagrant up/destroy commands using subprocess, with tests that mock the subprocess call to simulate outputs and errors.

subprocess unittest.mock vagrant
Python
import subprocess
from unittest.mock import patch, Mock


def run_vagrant(action: str) -> str:
    result = subprocess.run(
        ["vagrant", action],
        capture_output=True,
        text=True,
        check=False,
    )
    return result.stdout.strip()


def vagrant_wrapper(action: str) -> str:
    if action n…
14 0 Open
Automation & scripting easy

How to Simulate a Traceroute in Python

This Python script simulates a network traceroute by generating mock hop IPs, random delays, and a destination reach condition, useful for testing network scripts.

traceroute simulation network
Python
import random
import time

def simulate_traceroute(destination, max_hops=30):
    """Simulate a traceroute to a destination with mock hop delays."""
    print(f"Traceroute to {destination} ({max_hops} hops max):")
    for hop in range(1, max_hops + 1):
        # Mock IP address for the hop
        mock_ip = f"10.0.{ra…
15 0 Open
Automation & scripting easy

How to Strip EXIF Metadata from Images in Python

Remove EXIF metadata from image bytes using Pillow, with a mock JPEG generator for testing.

exif images metadata
Python
from PIL import Image
from PIL.ExifTags import TAGS
from io import BytesIO
import struct

def strip_exif(image_bytes, remove_metadata=True):
    """Remove EXIF metadata from image bytes."""
    img = Image.open(BytesIO(image_bytes))
    if remove_metadata:
        # Clear all metadata
        img.info.clear()
    # Sa…
13 0 Open
Automation & scripting easy

Mock Certbot Renewal in Python for Testing

Simulates a Let's Encrypt certificate renewal by writing a mock certificate file and printing realistic certbot CLI output, without calling the actual certbot.

certbot letsencrypt automation
Python
import subprocess
import sys
from datetime import datetime, timedelta
from pathlib import Path


def renew_cert(domain: str, output_dir: str = "certs") -> str:
    """Simulate a Let's Encrypt renewal with mock certbot output."""
    out = Path(output_dir)
    out.mkdir(parents=True, exist_ok=True)

    cert_path = out…
16 0 Open
Automation & scripting easy

Mock a Helm Upgrade Install Command in Python

Use unittest mock to simulate a Helm upgrade --install call for testing automation scripts without a real cluster.

mock helm testing
Python
from unittest.mock import MagicMock, patch


class HelmClient:
    def upgrade_install(self, release, chart, namespace="default"):
        # Simulates the helm upgrade --install command
        return f"Release {release} upgraded/installed in {namespace} using chart {chart}"


@patch("helm_client.HelmClient.upgrade_in…
13 0 Open
Automation & scripting easy

Mock systemctl Wrapper in Python for Service Testing

A Python class-based mock of systemctl that simulates start, stop, restart, and status operations for a service, useful for testing automation scripts.

systemctl mock automation
Python
import subprocess
import sys

class ServiceManager:
    def __init__(self, service_name):
        self.service_name = service_name
        self.status = "inactive"
    
    def start(self):
        self.status = "active"
        print(f"Starting {self.service_name}... OK")
    
    def stop(self):
        self.status …
14 0 Open
Automation & scripting easy

Run pytest and email summary in Python

Runs pytest via subprocess, extracts the test summary line, and sends it in an email (mocked for demonstration).

pytest subprocess email
Python
import smtplib
import subprocess
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart


def run_tests():
    """Run pytest and capture the summary output."""
    result = subprocess.run(
        ["pytest", "-q"],
        capture_output=True,
        text=True
    )
    return result.stdo…
12 0 Open
Automation & scripting easy

Toggle VPN Mock Network Manager Script in Python

Simulate a VPN manager with connect, disconnect, toggle, and status methods for testing or demo workflows.

vpn simulation automation
Python
import time

class MockVPNManager:
    def __init__(self):
        self.is_connected = False
        self.servers = ["us-west", "eu-central", "asia-east"]
        self.active_server = None

    def toggle(self):
        if self.is_connected:
            self.disconnect()
        else:
            self.connect()

    d…
11 0 Open
Data pipelines & processing easy

Generate a Mock CDC Changelog in Python

Simulate a CDC changelog with INSERT, UPDATE, and DELETE operations, timestamps, and record snapshots for testing data pipelines.

cdc changelog mock-data
Python
import json
from datetime import datetime, timedelta


def generate_mock_changelog(records, operations=("INSERT", "UPDATE", "DELETE")):
    """Simulate a CDC changelog from a list of record snapshots."""
    base_time = datetime(2025, 1, 1, 8, 0, 0)
    changelog = []
    for idx, record in enumerate(records):
       …
15 0 Open
Data pipelines & processing easy

Test a Python Pipeline with Fixture Sample Rows

Test pipeline functions with sample rows provided by a pytest fixture, verifying required keys and value constraints.

pytest fixtures data-pipelines
Python
import pytest


def get_value(data: dict, key: str):
    return data.get(key)


def sample_rows():
    return [
        {"name": "Alice", "age": 30, "city": "London"},
        {"name": "Bob", "age": 25, "city": "Paris"},
        {"name": "Charlie", "age": 35, "city": "Berlin"},
    ]


@pytest.fixture
def sample_data(…
16 0 Open
Git + Python easy

Create a Mock GitHub Release API in Python for Testing gh CLI

Build an in-memory GitHub Releases API mock that mimics create_release and list_releases for unit testing gh CLI stubs without network calls.

mock-api github testing
Python
import json
from unittest.mock import patch, Mock

class GitHubReleaseAPI:
    """Mock GitHub Releases API for testing gh CLI stub behavior."""
    
    def __init__(self):
        self.releases = {}
        self.counter = 1
    
    def create_release(self, repo, tag, name=None, notes=None):
        release_id = self…
16 0 Open
Git + Python easy

How to Mock Git Worktree Creation in Python

Create a mock Git worktree setup with parallel branch directories and state files for testing or simulation.

git worktree mock
Python
import os
import tempfile
from pathlib import Path

def create_mock_worktree(base_dir: Path, branches: list[str]) -> dict[str, Path]:
    """
    Mock Git worktree creation: creates parallel directories for each branch
    under the base directory, simulating independent worktrees.
    """
    worktrees = {}
    for b…
14 0 Open
Git + Python easy

How to Mock subprocess.run in Python Tests

Mock subprocess.run to test a Git submodule update command without executing it in your test suite.

unittest.mock subprocess git
Python
import subprocess
from unittest.mock import Mock, patch

def update_submodules():
    subprocess.run(["git", "submodule", "update", "--init", "--recursive"], check=True)

with patch("subprocess.run") as mock_run:
    mock_run.return_value = Mock(returncode=0)
    update_submodules()
    mock_run.assert_called_once_wit…
13 0 Open
Cloud + Python easy

Generate an Idempotency-Key header mock with UUID in Python

This code provides a mock idempotency service that generates a UUID-based Idempotency-Key header token and validates it, useful for simulating production API behavior in tests.

uuid idempotency mock
Python
import uuid

class MockIdempotencyService:
    def __init__(self):
        self._tokens = {}

    def get_token(self, header_name="Idempotency-Key"):
        token = str(uuid.uuid4())
        self._tokens[header_name] = token
        return token

    def validate(self, header_name="Idempotency-Key"):
        return s…
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.