Python Code
Samples
Medium snippets you can copy, study, and run in the browser editor.
How to Build a CSV Comparison Tool That Highlights Every Changed Cell in Python
Read two CSV files with DictReader, compare cell by cell, and return a list of dictionaries describing each changed cell using only the standard library.
import csv
from pathlib import Path
def csv_cell_diff(file_a: str, file_b: str) -> list[dict]:
rows_a = list(csv.DictReader(Path(file_a).open('r', newline='')))
rows_b = list(csv.DictReader(Path(file_b).open('r', newline='')))
if not rows_a or not rows_b:
return []
columns = list(rows_a[0].key…
How to Compare Two Files by Content Hash Equality in Python
Compares two files by hashing their contents with SHA-256, skipping the hash if file sizes differ, and returns whether they are identical.
import hashlib
from pathlib import Path
def file_hash(path: Path, chunk_size: int = 8192) -> str:
sha256 = hashlib.sha256()
with path.open("rb") as f:
for chunk in iter(lambda: f.read(chunk_size), b""):
sha256.update(chunk)
return sha256.hexdigest()
def files_are_identical(file_a: Pat…
How to Use fcntl for Exclusive File Locking in Python
This code demonstrates how to acquire an exclusive advisory lock on a file using fcntl.flock with a non-blocking flag, simulate work, then release the lock.
import fcntl
import os
import tempfile
import time
def acquire_exclusive_lock(filepath):
fd = os.open(filepath, os.O_RDWR | os.O_CREAT)
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
print(f"Exclusive lock acquired on {filepath}")
time.sleep(1) # Simulate work while holding the l…
How to Compare Two GitHub Repositories and Highlight Differences in Python
Fetch metadata from two GitHub repositories using the GitHub API and compare key attributes like stars, forks, license, and language, printing any differences.
import requests
import json
from pathlib import Path
def fetch_repo_data(owner, repo_name):
"""Fetch repository metadata from GitHub API."""
url = f"https://api.github.com/repos/{owner}/{repo_name}"
response = requests.get(url)
response.raise_for_status()
return response.json()
def compare_repos(…
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.
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")
…
How to Mock subprocess.run for Black Formatter in Python
Use unittest.mock to simulate subprocess.run calls in a Python function that runs the Black formatter, allowing isolated testing without executing external commands.
import subprocess
from unittest.mock import Mock, patch
def run_black_formatter(file_path: str, check_only: bool = False) -> dict:
"""Run black formatter on a file via subprocess."""
cmd = ["black", "--check" if check_only else "-", file_path]
result = subprocess.run(cmd, capture_output=True, text=True)
…
How to Use threading.local for Per-Thread Data in Python
Use threading.local to keep thread-specific data — each thread gets its own copy of the attribute, so values don't leak between threads.
import threading
import time
local_storage = threading.local()
def worker(name):
local_storage.name = name
time.sleep(0.1)
print(f"Thread {threading.current_thread().name}: {local_storage.name}")
if __name__ == "__main__":
threads = []
for i in range(3):
t = threading.Thread(target=worke…
How to Compare Execution Speed Between Python Functions
Measure and compare the average execution time of multiple Python functions using a reusable benchmark helper with time.perf_counter.
import time
import random
def method_a(values):
"""Sort using built-in sorted."""
return sorted(values)
def method_b(values):
"""Sort using list's sort method."""
values_copy = values[:]
values_copy.sort()
return values_copy
def method_c(values):
"""Sort manually using bubble sort (slow,…
Use pytest fixture to mock a database connection in Python
This code shows how to use a pytest fixture and unittest.mock to replace a database connection with a Mock, enabling isolated tests without a real database.
import pytest
import sqlite3
from unittest.mock import Mock
class Database:
def __init__(self, connection):
self.connection = connection
def get_user(self, user_id):
cursor = self.connection.cursor()
cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,))
return cursor.…
Implement Bulkhead Thread Pool Isolation in Python
Create isolated thread pools with a bulkhead pattern to protect different services from cascading failures.
import threading
import time
import random
from concurrent.futures import ThreadPoolExecutor
class Bulkhead:
"""Simple bulkhead isolation: separate thread pools for different tasks."""
def __init__(self, max_workers):
self.executor = ThreadPoolExecutor(max_workers=max_workers)
self.active = …
How to Filter Query Parameters by Operator in Python
Parse a URL query string and keep only parameters with allowed comparison operators like eq, gt, and lt.
from urllib.parse import urlparse, parse_qs
def filter_operators(query_string, allowed=("eq", "gt", "lt")):
parsed = urlparse(query_string)
params = parse_qs(parsed.query)
filtered = {}
for key, values in params.items():
if "__" in key:
field, op = key.rsplit("__", 1)
i…
How to Implement a Bulkhead Pattern with Threading in Python
Implement a bulkhead pattern in Python that isolates concurrent tasks with a bounded semaphore, limiting active workers to prevent resource exhaustion.
import threading
import time
import random
class Bulkhead:
def __init__(self, workers: int):
self._semaphore = threading.BoundedSemaphore(workers)
self._lock = threading.Lock()
self._active = 0
def run(self, task):
with self._semaphore:
with self._lock:
…
How to Send Messages to a Dead Letter Queue in Python
Simulates a poison message queue that retries failed messages up to a limit before moving them to a dead letter queue.
import json
class PoisonMessageQueue:
def __init__(self, max_retries=3):
self.dlq = []
self.max_retries = max_retries
self.processed_count = 0
self.failed_count = 0
def process_message(self, message_body):
if "poison" in message_body:
self.failed_count += 1…
Bulkhead Thread Pool per Service Mock in Python
Simulates a bulkhead pattern with per-service thread pools and semaphore-based rejection to isolate failures between dependent services.
import threading
import time
import random
from concurrent.futures import ThreadPoolExecutor
class ServiceBulkhead:
def __init__(self, name, max_threads, max_queue):
self.name = name
self.executor = ThreadPoolExecutor(max_workers=max_threads)
self.semaphore = threading.Semaphore(max_thread…
Bloom Filter Join Mock in Python
A mock hash join that uses a Bloom filter to pre-filter one table before performing an exact match, reducing the number of comparisons in large dataset joins.
import hashlib
import random
import string
class BloomFilter:
def __init__(self, size: int = 200, num_hashes: int = 3):
self.bits = [False] * size
self.size = size
self.num_hashes = num_hashes
def _hashes(self, item: str):
result = []
for seed in range(self.num_hashes…
How to Mock ROC AUC in Python
Compute ROC AUC from scratch in Python using pairwise comparisons between positive and negative score distributions, ideal for testing ML models without sklearn.
import random
from math import comb
def mock_roc_auc(scores, labels):
"""Compute mock ROC AUC by simulating a classifier's score distribution."""
random.seed(42)
n = len(labels)
pos_scores = [scores[i] for i in range(n) if labels[i] == 1]
neg_scores = [scores[i] for i in range(n) if labels[i] == …
How to Mock SQLite executemany When Batch Inserting in Python
Batch insert many rows into SQLite with executemany and mock the cursor for isolated tests.
import sqlite3
from unittest.mock import Mock, patch
def insert_users(conn, users):
"""Insert multiple user records using executemany."""
cursor = conn.cursor()
cursor.executemany(
"INSERT INTO users (name, age) VALUES (?, ?)",
users
)
conn.commit()
return cursor.rowcount
if _…
How to Hash Passwords and Authenticate Users in Python
A beginner-friendly dataclass-based design that hashes passwords with PBKDF2 and verifies them securely using constant-time comparisons.
import hashlib
import hmac
import secrets
from dataclasses import dataclass
from typing import Optional
@dataclass
class User:
id: int
username: str
password_hash: str
salt: str
def hash_password(password: str) -> tuple[str, str]:
salt = secrets.token_hex(16)
password_hash = hashlib.pbkdf2_…
How to Mock Environment Variables in Python
A context manager that injects and restores environment variables for isolated testing of config-dependent code.
import os
class EnvInjector:
def __init__(self, mock_vars=None):
self.mock_vars = mock_vars or {}
self.original = {}
def __enter__(self):
for key, value in self.mock_vars.items():
if key in os.environ:
self.original[key] = os.environ[key]
os.env…
How to Expand a Contract and Migrate Data in Python
Expand an old data contract by renaming fields and adding defaults, then migrate to a final version with deepcopy isolation.
import json
from copy import deepcopy
# Mock data representing a user record (old contract)
old_contract = {
"id": 1,
"name": "Alice",
"email": "alice@example.com",
"age": 30,
"status": "active"
}
# Expanded contract: adds fields with defaults and renames some fields
expand_rules = {
"id": "u…
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.