Python Code
Samples
Medium snippets you can copy, study, and run in the browser editor.
Redact secrets from log message formatter in Python
Build a custom logging.Formatter that masks passwords, API keys, and credit card numbers in log output.
import re
import logging
class RedactingFormatter(logging.Formatter):
"""Formatter that masks sensitive data in log messages."""
SENSITIVE_PATTERNS = [
(re.compile(r'password[=:]\s*\S+', re.IGNORECASE), 'password=[REDACTED]'),
(re.compile(r'api[_-]?key[=:]\s*\S+', re.IGNORECASE), 'api_key…
How to Merge Sorted Chunk Files in Python
Merge multiple sorted text files into one sorted output file using a heap for efficient k-way merging.
import heapq
def merge_sorted_chunks(chunks, output_path):
"""Merge multiple sorted iterables into single sorted output file."""
with open(output_path, "w") as out_f:
# Open all chunk files
handles = [open(chunk, "r") for chunk in chunks]
try:
# Heap of (value, index) tupl…
Join two CSV files on shared key column in Python
Merge rows from two CSV files by a common key column, outputting combined records to a new file.
import csv
def join_csv(file1, file2, key, output="joined.csv"):
# Read first CSV into dict keyed by the join column
with open(file1, newline="") as f1:
reader1 = csv.DictReader(f1)
data1 = {row[key]: row for row in reader1}
# Read second CSV and merge matching rows
with open(file2, n…
Find Zombie Processes on Linux with Python
Parse the output of `ps -eo pid,stat,comm` to detect processes in zombie state (Z) on a Linux system and report their PIDs and commands.
#!/usr/bin/env python3
import os
import subprocess
def find_zombie_processes():
"""Find zombie processes (state 'Z') running on Linux."""
try:
result = subprocess.run(['ps', '-eo', 'pid,stat,comm'], capture_output=True, text=True, check=True)
zombies = []
for line in result.stdout.stri…
How to Monitor USB Device Connections in Python
A Python utility that monitors USB device connections and disconnections by comparing output of the lsusb command at regular intervals.
import time
import subprocess
import os
def get_usb_devices():
"""Return list of currently connected USB devices (Linux)."""
try:
result = subprocess.run(['lsusb'], capture_output=True, text=True, check=True)
return result.stdout.strip().split('\n')
except (subprocess.CalledProcessError, F…
How to Make a Git Commit Heatmap by Hour in Python
Parse a git log output and count commits by weekday and hour, then print a compact heatmap table.
import re
from collections import Counter
from datetime import datetime
def parse_commits(log_text):
"""Parse git log lines and count commits by (weekday, hour)."""
pattern = re.compile(r"^Date:\s+(.+)$")
counts = Counter()
for line in log_text.splitlines():
match = pattern.match(line)
…
Mock CDK Synth Output in Python for Template Testing
Simulate AWS CDK synth output with MagicMock to test or preview CloudFormation templates without running a real CDK app.
import json
from unittest.mock import MagicMock
def mock_cdk_synth() -> dict:
"""Simulate AWS CDK synth output for a simple S3 bucket."""
cdk_app = MagicMock()
cdk_app.synth.return_value.template = {
"Resources": {
"MyBucket": {
"Type": "AWS::S3::Bucket",
…
How to Mock CLI Output in Typer with unittest.mock
Mock and capture Typer CLI output using unittest.mock.patch and io.StringIO for testing command-line applications.
import typer
from unittest.mock import patch
import io
app = typer.Typer()
@app.command()
def greet(name: str, age: int = 18, uppercase: bool = False):
"""Greet a person with optional formatting."""
message = f"Hello {name}, age {age}"
if uppercase:
message = message.upper()
typer.echo(messag…
How to Use a Bounded Buffer with threading.Condition in Python
Implement a thread-safe bounded buffer using threading.Condition and show a producer–consumer example with exact output.
import threading
import time
import random
class BoundedBuffer:
def __init__(self, capacity):
self.capacity = capacity
self.buffer = []
self.condition = threading.Condition()
def put(self, item):
with self.condition:
while len(self.buffer) >= self.capacity:
…
Characterization Test for Legacy Python Code
Capture the exact output of a legacy Python function for known inputs, creating a characterization test that documents current behavior before refactoring.
def legacy_behavior(value):
"""Legacy function that returns a tuple with unconventional types."""
if value == "special":
return None, "legacy-special"
elif value > 100:
return value, "large"
elif value > 0:
return value * 2, "positive-doubled"
elif value == 0:
…
How to Run Test Coverage with pytest-cov in Python
Run pytest with coverage reporting using pytest-cov on a temporary project and see line-by-line coverage output.
import os
import subprocess
import tempfile
from pathlib import Path
def sample_function(x: int) -> int:
"""A simple function to demonstrate coverage."""
if x > 0:
return x * 2
else:
return -x
def run_pytest_with_coverage() -> str:
"""Run pytest with coverage on a temp project and r…
How to Snapshot Test JSON with Mock in Python
Use pytest-snapshot to capture the exact output of a JSON-loading function, with and without mocking json.loads, so future changes are automatically detected.
import json
from unittest.mock import Mock, patch
import pytest
def load_config(data):
config = json.loads(data)
return {"host": config["host"], "port": config["port"]}
def test_load_config_snapshot(snapshot):
mock_data = json.dumps({"host": "localhost", "port": 8080, "extra": "ignored"})
result = …
Mock Watermark Late Event Side Output in Python
Simulates watermarking in a streaming pipeline by classifying events as on-time or late using timestamps and delays.
from datetime import datetime, timedelta
from typing import List, Tuple
def watermark_mock(
events: List[Tuple[datetime, str]], watermark_delay: timedelta, max_delay: timedelta
) -> Tuple[List[Tuple[datetime, str]], List[Tuple[datetime, str]]]:
"""Simulate watermarking: events arriving on time vs. late by ch…
How to Build a Python Latency Histogram with Mock Buckets
This code implements a mock latency histogram that records request durations into configurable buckets and outputs counts, total, and average latency.
import time
import random
from collections import Counter
class LatencyHistogram:
def __init__(self, buckets):
self.buckets = sorted(buckets)
self.counts = Counter()
self.total = 0
self.sum_latency = 0
def record(self, latency_ms):
for i, boundary in enumerate(self.bu…
How to Mock Kedro Pipeline Nodes in Python
Create a modular Kedro pipeline with node functions, namespacing, and input/output mapping to mock pipeline execution locally.
from kedro.pipeline import Pipeline, node
from kedro.pipeline.modular_pipeline import pipeline as modular_pipeline
def preprocess(data: list) -> list:
"""Clean data by removing None values."""
return [item for item in data if item is not None]
def transform(data: list) -> list:
"""Add 1 to each numeric…
Mock a Flyte ML workflow in Python
Build a lightweight mock of a Flyte ML pipeline with dataclasses and a simple execution loop that passes outputs between tasks.
from dataclasses import dataclass, field
from typing import List, Dict, Optional
import time
@dataclass
class FlyteTask:
name: str
inputs: Dict = field(default_factory=dict)
outputs: Dict = field(default_factory=dict)
def run(self) -> Dict:
time.sleep(0.1) # simulate work
return sel…
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.