Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

321 matches
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 medium

Mount ISO Loop Device Mock Script in Python

Simulate ISO mounting with a loop device using a mock class — useful for testing scripts that depend on mount/unmount without actual system privileges.

iso loop-device mock
Python
import os
import tempfile
from dataclasses import dataclass
from pathlib import Path

@dataclass
class LoopDevice:
    path: str
    iso_path: str
    mounted: bool = False

    def mount(self, mount_point: str):
        if self.mounted:
            raise RuntimeError(f"Loop device {self.path} already mounted")
      …
14 0 Open
Automation & scripting easy

Restore sqlite from latest backup file in Python

This script finds the most recently modified backup file in a directory and restores it to the main database path, then verifies the restored data.

sqlite backup file-io
Python
import sqlite3
import glob
import os
import shutil

def restore_latest_backup(db_path, backup_dir):
    backups = sorted(glob.glob(os.path.join(backup_dir, "*.db")), key=os.path.getmtime)
    if not backups:
        raise FileNotFoundError("No backup files found")
    latest = backups[-1]
    shutil.copy2(latest, db_p…
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

Stress CPU Threads with a Mock Compute in Python

Simulates CPU-intensive work across multiple threads to test how Python schedules parallel compute.

threading cpu-stress parallelism
Python
import threading
import time


def stress_cpu(iterations: int):
    result = 0
    for i in range(iterations):
        result += i * i % 1000
    return result


def run_mock_stress(thread_count: int, iterations: int):
    threads = []
    for tid in range(thread_count):
        t = threading.Thread(target=lambda: str…
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 medium

Map Partition Over Chunks in Python with Multiprocessing and Mock

Process data in chunks across multiple CPU cores using multiprocessing Pool.map, and mock the chunk function to test partitioning behavior without heavy computation.

multiprocessing chunking parallel
Python
from multiprocessing import Pool
from unittest.mock import patch, Mock

def process_chunk(chunk):
    return [x * x for x in chunk]

def map_partition_over_chunks(data, chunk_size, process_func=process_chunk):
    chunks = [data[i:i + chunk_size] for i in range(0, len(data), chunk_size)]
    with Pool() as pool:
     …
12 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

Bump Semantic Version Git Tag in Python

Automatically find the latest Git tag and compute the next patch release using semantic versioning (semver) in Python.

git semver versioning
Python
from re import match
from subprocess import run

SEMVER_PATTERN = r"^v(?P<major>0|[1-9]\d*)\.(?P<minor>0|[1-9]\d*)\.(?P<patch>0|[1-9]\d*)(?:-(?P<prerelease>[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+(?P<buildmetadata>[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$"


def get_latest_tag() -> str:
    result = run(["git", "describe…
14 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 medium

How to Build a Branch Protection Audit Mock API in Python

A mock HTTP API that serves branch protection rules for repositories and audits them for compliance, built with Python's standard library.

git api http-server
Python
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse, parse_qs

REPOSITORIES = {
    "alpha": {
        "default_branch": "main",
        "branches": ["main", "develop", "feature-x"],
        "protection_rules": {
            "main": {"required_reviews": 2, "dismiss_…
9 0 Open
Git + Python medium

How to Get Current Git Branch Name in Python with Mock Subprocess

Mocks the subprocess call to reliably test the current git branch name retrieval using GitPython.

git gitpython subprocess
Python
import subprocess
from unittest.mock import patch, MagicMock
from git import Repo
import os


def get_current_branch(repo_path="."):
    """Get the current branch name of a git repository."""
    repo = Repo(repo_path)
    return repo.active_branch.name


if __name__ == "__main__":
    # Mock subprocess to control the…
12 0 Open
Git + Python medium

How to Mock Git Cherry-Pick in Python for Tests

Mock the `repo.git.cherry_pick` method with `unittest.mock` to test a Git cherry-pick helper without a real repository.

git mock unittest
Python
from unittest.mock import patch, MagicMock

class GitCherryPicker:
    def __init__(self):
        self.applied_commits = []
    
    def cherry_pick(self, commit_hash, repo):
        try:
            result = repo.git.cherry_pick(commit_hash)
            self.applied_commits.append(commit_hash)
            return f"A…
14 0 Open
Git + Python medium

How to Mock Git Pre-commit Hooks (black and ruff) in Python

Mock subprocess to test black and ruff pre-commit commands without actually running them, verifying exit codes.

git pre-commit mocking
Python
import sys
import subprocess
from unittest.mock import patch

def run_hook(command: list[str]) -> int:
    with patch("subprocess.run") as mock_run:
        mock_run.return_value.returncode = 0
        mock_run.return_value.stdout = f"Mocked: {' '.join(command)}"
        result = subprocess.run(command, capture_output…
16 0 Open
Git + Python medium

How to Mock Git Stash and Pop in Python

Mock Git stash, apply, and pop operations using unittest.mock so you can test Git automation without touching a real repository.

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

def stash_and_pop(repo):
    """Mock a stash operation and then pop it back."""
    repo.git.stash("save", "WIP: temp changes")
    stashed_output = repo.git.stash("list")
    
    # Simulate the stash was applied, then pop
    repo.git.stash("apply", "stash@{0}")
    …
14 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 medium

How to Mock open() in Python Using unittest.mock.patch

This code shows how to use unittest.mock.patch with mock_open to test a function that checks if a Git patch can be reverse-applied by reading file content.

unittest mocking git
Python
import unittest
from unittest.mock import patch, mock_open


def apply_reverse_check(file_path, expected_patch):
    """
    Check if a patch can be reverse-applied by comparing file content
    with the expected patch's reverse result.
    """
    try:
        with open(file_path, "r") as f:
            content = f.r…
15 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
Git + Python medium

Mock smtplib to Test Patch Email Series in Python

Simulate sending a numbered series of patch emails with smtplib and verify the calls using unittest.mock without a real mail server.

smtplib unittest.mock email
Python
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from unittest.mock import patch, Mock

def send_patch_series(subject_prefix, patches, smtp_host="localhost", smtp_port=25):
    """Simulate sending a series of patch emails."""
    for i, patch_content in enumerate(patch…
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
Cloud + Python easy

How to Create a Mock STS AssumeRole Credentials Dict in Python

Build a realistic AWS STS AssumeRole response dict with temporary credentials, expiry time, and assumed role ARN for local testing.

aws sts mocking
Python
import json
from datetime import datetime, timedelta, timezone


def mock_sts_credentials(role_arn, session_name, duration=3600):
    now = datetime.now(timezone.utc)
    expiration = now + timedelta(seconds=duration)

    credentials = {
        "Credentials": {
            "AccessKeyId": "ASIAEXAMPLEACCESSKEY",
    …
14 0 Open
Cloud + Python medium

How to Mock AWS SQS Send Receive Delete in Python

Build an in-memory mock of the SQS send, receive, and delete message flow for local testing.

aws sqs mock
Python
import json
from collections import deque
from uuid import uuid4


class MockSQSQueue:
    def __init__(self, name):
        self.name = name
        self._messages = deque()
        self._in_flight = {}

    def send_message(self, body, attributes=None):
        message_id = str(uuid4())
        message = {
         …
14 0 Open
Cloud + Python easy

How to Mock AWS Secrets Manager in Python

Create a lightweight mock of AWS Secrets Manager's get_secret_value API to test secret retrieval without cloud dependencies.

aws secrets-manager mock
Python
import json
from typing import Optional


class MockSecretsManager:
    """A simple mock of AWS Secrets Manager's get_secret_value API."""

    def __init__(self):
        self._secrets: dict[str, str] = {}

    def create_secret(self, secret_id: str, secret_value: str) -> None:
        """Store a secret value under a…
14 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.