Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
Strings & text
Format, split, join, parse, and clean text — everyday Python string patterns.
Automatically Detect Weak Passwords from Large Password Lists in Python
This Python script identifies weak passwords from a list by checking length, common patterns, sequential characters, and uniform characters, returning those that fail the security checks.
import re
COMMON_PASSWORDS_FILE = "common_passwords.txt"
def is_weak(password):
# Check length
if len(password) < 8:
return True
# Check for common patterns
if password.lower() in {"password", "123456", "qwerty", "letmein", "admin", "welcome"}:
return True
# Check for sequential c…
Build CSV row from Python list with proper quoting
Converts a list of fields into a properly quoted CSV row string using the csv module.
import csv
import io
def build_csv_row(fields):
output = io.StringIO()
writer = csv.writer(output)
writer.writerow(fields)
return output.getvalue().rstrip("\r\n")
if __name__ == "__main__":
fields = ["Alice", "Smith", "123 Main St, Apt 4B", "alice@example.com"]
print(build_csv_row(fields))
Build a Secure Password Strength Checker in Python
A Python function that evaluates password strength based on length and character diversity, returning Weak, Moderate, or Strong.
import re
def password_strength(password: str) -> str:
score = 0
if len(password) >= 8:
score += 1
if re.search(r'[a-z]', password):
score += 1
if re.search(r'[A-Z]', password):
score += 1
if re.search(r'\d', password):
score += 1
if re.search(r'[!@#$%^&*(),.?":…
Convert Natural Language Dates to Datetime in Python
Parse common natural language date phrases like 'tomorrow' or 'in 3 days' into Python datetime objects using regex and timedelta.
from datetime import datetime, timedelta
import re
def parse_natural_date(text: str) -> datetime:
"""Convert common natural language date expressions to datetime objects."""
now = datetime.now()
text = text.lower().strip()
# Handle relative dates
patterns = {
r"today": now,
r"…
Count Characters, Words, and Lines in Python Text
Counts characters, words, lines, and the most common words in a given string using Python's standard library.
from collections import Counter
def count_data(text):
"""Count characters, words, lines, and most common words in text."""
char_count = len(text)
word_count = len(text.split())
line_count = text.count("\n") + 1
word_freq = Counter(text.lower().split())
most_common = word_freq.most_common(3)
…
Extract Data from Strings in Python: Beginner's Guide
A beginner-friendly helper that splits a comma-separated string into a list, shows word count, and extracts the first and last words using Python's split() and join() methods.
text = "python,string,extract,beginner"
words = text.split(",")
print("Full text:", text)
print("Word count:", len(words))
print("First word:", words[0])
print("Last word:", words[-1])
joined = " | ".join(words)
print("Joined with separator:", joined)
Lists & loops
Iterate, transform, and combine sequences with readable loop patterns.
Check if List is Sorted Ascending in Python
Verify that a list is sorted in ascending order using the all() function and a generator expression.
def is_sorted_ascending(lst):
return all(lst[i] <= lst[i + 1] for i in range(len(lst) - 1))
if __name__ == "__main__":
test_lists = [
[1, 2, 3, 4, 5],
[1, 3, 2, 4, 5],
[5, 4, 3, 2, 1],
[1, 1, 2, 2, 3],
[10],
[]
]
for lst in test_lists:
print(f"{l…
Compare Two Lists in Python: Common, Only in First, Only in Second
A beginner-friendly helper that loops over two lists and returns items common to both, items only in the first list, and items only in the second list.
def compare_lists(list1, list2):
common = []
only_in_first = []
only_in_second = []
for item in list1:
if item in list2:
common.append(item)
else:
only_in_first.append(item)
for item in list2:
if item not in list1:
only_in_second…
Convert a List of Integers to a Comma-Separated String in Python
Convert a list of integers into a single comma-separated string using a generator expression and str.join.
def ints_to_comma_string(numbers):
return ",".join(str(num) for num in numbers)
if __name__ == "__main__":
numbers = [1, 2, 3, 4, 5]
result = ints_to_comma_string(numbers)
print(result)
Enumerate a Python List with a Custom Start Index
Iterate over a list with an index that starts at a custom value (like 5) using Python's built-in enumerate() function with the start parameter.
fruits = ["apple", "banana", "cherry", "date"]
for index, fruit in enumerate(fruits, start=5):
print(f"{index}: {fruit}")
Extract Data by Type from a List in Python: Numbers and Strings
Loop through a mixed list to filter out numeric and string values into separate lists.
def extract_numbers(items):
"""Extract all numeric values from a mixed list."""
numbers = []
for item in items:
if isinstance(item, (int, float)) and not isinstance(item, bool):
numbers.append(item)
return numbers
def extract_strings(items):
"""Extract all string values from a…
Find All Occurrences of an Item in a Python List
Loop through a list with enumerate() to collect the index of every match for a target value.
def find_all(data, target):
"""Return indices of every occurrence of target in a list."""
indices = []
for index, item in enumerate(data):
if item == target:
indices.append(index)
return indices
if __name__ == "__main__":
sample = [10, 20, 30, 20, 40, 20, 50]
target_value …
Functions & basics
Reusable building blocks — parameters, returns, scope, and clear function design.
Add Type Hints to Function Parameters and Return in Python
Add type hints to function parameters and return values in Python for clearer, more maintainable code using the typing module.
from typing import List, Optional, Dict
def average(numbers: List[float]) -> float:
return sum(numbers) / len(numbers)
def full_name(first: str, last: Optional[str] = "") -> str:
return f"{first} {last}".strip()
def build_user(name: str, age: int, email: Optional[str] = None) -> Dict[str, object]:
us…
Benchmark list append vs comprehension in Python
This micro-benchmark compares the speed of building a list with a for loop and append versus a list comprehension, using the timeit module to get precise timings.
import timeit
# Build a list of the first 1,000,000 integers using append in a loop
def append_loop(n=1_000_000):
result = []
for i in range(n):
result.append(i)
return result
# Build the same list using a list comprehension
def comprehension(n=1_000_000):
return [i for i in range(n)]
if __n…
Build a Context Manager in Python with contextlib.contextmanager
Create a reusable context manager that safely opens and closes files using the contextlib contextmanager decorator.
from contextlib import contextmanager
@contextmanager
def managed_file(filename, mode='r'):
"""Context manager that opens and closes a file safely."""
file = open(filename, mode)
yield file
file.close()
if __name__ == "__main__":
# Write a sample file
with managed_file("sample.txt", "w") as f…
Build a Progress Callback Function for Loops in Python
Create a reusable progress callback that receives per-step data and lets callers log or update a UI as a loop runs.
def run_with_progress(items, desc="Processing", step_callback=None):
"""Run a loop with progress updates via callback."""
total = len(items)
for idx, item in enumerate(items):
# Process the item (simulated work here)
result = item * 2
# Build progress data dictionary
if ste…
Cache expensive function with lru_cache in Python
Use functools.lru_cache to memoize an expensive recursive function and show the dramatic speedup on repeated calls.
from functools import lru_cache
import time
@lru_cache(maxsize=128)
def expensive_operation(n):
"""Simulate an expensive Fibonacci-like calculation."""
if n < 2:
return n
return expensive_operation(n - 1) + expensive_operation(n - 2)
if __name__ == "__main__":
# First call (uncached) - take…
Calculate Time Difference Across Time Zones in Python
Compute the current time difference in hours between two time zones given their UTC offsets using Python's datetime and timezone modules.
from datetime import datetime, timezone, timedelta
def time_difference(from_tz_offset, to_tz_offset):
"""
Calculate time difference in hours between two time zones given their offsets from UTC.
Offsets are in hours (e.g., -5 for EST, +5.5 for IST).
"""
tz1 = timezone(timedelta(hours=from_tz_offset…
Errors & debugging
Handle failures gracefully, raise helpful errors, and debug with confidence.
Catch RecursionError and Fail Gracefully in Python
Wrap a recursive function call in a try-except block to catch RecursionError and print a graceful failure message instead of crashing.
def compute_factorial_recursive(n):
"""Compute factorial recursively, raising RecursionError for deep recursion."""
if n == 0:
return 1
return n * compute_factorial_recursive(n - 1)
if __name__ == "__main__":
try:
result = compute_factorial_recursive(10000)
print(f"Factorial c…
Catch ValueError and print friendly message in Python
Wrap an int() call in a try/except block and print a friendly message when ValueError is raised.
try:
number = int("not_a_number")
except ValueError:
print("That's not a valid number. Please enter digits only.")
Collect Multiple Validation Errors in Python Before Raising
A chainable Validator class that accumulates all validation errors and raises them together in a single exception.
class ValidationError(Exception):
pass
class Validator:
def __init__(self):
self.errors = []
def validate_required(self, value, field_name):
if not value:
self.errors.append(f"{field_name} is required")
return self
def validate_email(self, email):
…
Handle ValueError and ZeroDivisionError in Python with try except
Learn how to catch ValueError and ZeroDivisionError in Python with a practical safe_divide function and demonstrate error handling for invalid conversions.
def safe_divide(numerator, denominator):
try:
result = numerator / denominator
except ValueError as e:
print(f"ValueError caught: {e}")
return None
except ZeroDivisionError:
print("Cannot divide by zero!")
return None
return result
# Test cases
print(safe_divide…
How to Add a Correlation ID to Logging Records in Python
Attach a unique correlation ID to every log record using a custom logging.Filter, making distributed request tracking traceable.
import logging
import uuid
from dataclasses import dataclass, field
@dataclass
class CorrelationIdFilter(logging.Filter):
correlation_id: str = field(default_factory=lambda: str(uuid.uuid4()))
def filter(self, record: logging.LogRecord) -> bool:
record.correlation_id = self.correlation_id
re…
How to Assert Preconditions with Descriptive Messages in Python
Use Python's assert statement with a custom message to validate function preconditions and fail fast with clear diagnostics.
def divide(dividend, divisor):
assert divisor != 0, f"Divisor must be non-zero, got {divisor!r}"
return dividend / divisor
if __name__ == "__main__":
print(divide(10, 2))
try:
divide(10, 0)
except AssertionError as e:
print(f"AssertionError: {e}")
Files & data
Read and write files safely; parse JSON, CSV, and common text formats.
Append a Line to a Log File in Python
Append a line to a file using a context manager and Path.open().
from pathlib import Path
def append_to_log(filepath, message):
with Path(filepath).open("a") as log_file:
log_file.write(f"{message}\n")
if __name__ == "__main__":
log_path = "log.txt"
append_to_log(log_path, "First entry")
append_to_log(log_path, "Second entry")
# Verify contents
…
Audit File Permissions Across a Project in Python
Walks through every file and directory in a project tree and prints POSIX permissions plus owner UID.
import os
import stat
from pathlib import Path
def audit_file_permissions(project_root):
"""Walk through project_root and print path, owner, and permissions for every file."""
results = []
for root, dirs, files in os.walk(project_root):
for name in files + dirs:
full_path = os.path.joi…
Automatically Detect Corrupted Files Using SHA-256 Checksums in Python
Compute SHA-256 checksums of files and compare them to detect corruption in Python.
import hashlib
import os
def compute_sha256(filepath: str) -> str:
"""Compute SHA-256 checksum of a file."""
sha256 = hashlib.sha256()
with open(filepath, 'rb') as f:
for chunk in iter(lambda: f.read(4096), b''):
sha256.update(chunk)
return sha256.hexdigest()
def validate_file_int…
Automatically Highlight Data Validation Errors Inside Excel Files in Python
Load an Excel file with openpyxl, iterate over cells, and highlight invalid data (empty, negative) with a red fill and error message.
import openpyxl
from openpyxl.styles import PatternFill
from pathlib import Path
def highlight_validation_errors(filepath: str, output_path: str = None):
wb = openpyxl.load_workbook(filepath)
red_fill = PatternFill(start_color="FF0000", end_color="FF0000", fill_type="solid")
for sheet in wb.worksheet…
Build a Command-Line To-Do List Application with Data Persistence in Python
A persistent command-line to-do list that saves tasks as JSON, supporting add, show, toggle done, and quit commands.
import json
import os
TODO_FILE = "todos.json"
def load_todos():
if not os.path.exists(TODO_FILE):
return []
with open(TODO_FILE, "r") as f:
return json.load(f)
def save_todos(todos):
with open(TODO_FILE, "w") as f:
json.dump(todos, f, indent=2)
def show_todos(todos):
if not…
Build a File Index by Relative Path Hash Map in Python
Recursively walk a directory and map normalized relative paths to absolute file paths using a defaultdict hash map.
import os
from collections import defaultdict
def build_file_index(root_dir):
index = defaultdict(list)
for dirpath, dirnames, filenames in os.walk(root_dir):
for filename in filenames:
full_path = os.path.join(dirpath, filename)
relative_path = os.path.relpath(full_path, roo…
Dictionaries & sets
Key–value maps, uniqueness, counting, grouping, and fast lookups.
Build a Case-Insensitive Dict with a Wrapper Class in Python
Create a custom dict subclass that treats keys as case-insensitive by normalizing them to lowercase, with a full set of common dict methods.
class CaseInsensitiveDict:
def __init__(self, data=None):
self._data = {}
if data:
self.update(data)
def __setitem__(self, key, value):
self._data[str(key).lower()] = value
def __getitem__(self, key):
return self._data[str(key).lower()]
def __delitem__(sel…
Build a defaultdict histogram of categories in Python
Count occurrences of each category in a list using collections.defaultdict(int) for automatic initialization.
from collections import defaultdict
def build_category_histogram(items):
"""Count occurrences of each category in a list of items."""
histogram = defaultdict(int)
for item in items:
histogram[item] += 1
return dict(histogram)
if __name__ == "__main__":
categories = ["fruit", "vegetable", …
Build adjacency dict graph from edges in Python
Convert a list of edges into an undirected adjacency dictionary, mapping each node to its neighbors, with sorted output.
def build_adjacency_dict(edges):
graph = {}
for u, v in edges:
if u not in graph:
graph[u] = []
if v not in graph:
graph[v] = []
graph[u].append(v)
graph[v].append(u)
return graph
if __name__ == "__main__":
edges = [(1, 2), (2, 3), (3, 4), (4, 1)…
Build an OrderedDict insertion order demo in Python 3
Demonstrate how OrderedDict preserves insertion order, how updates keep position, and how re-insertion moves keys to the end.
from collections import OrderedDict
def demo_ordered_dict():
# Create an OrderedDict and insert items in a specific order
ordered = OrderedDict()
ordered['banana'] = 3
ordered['apple'] = 2
ordered['cherry'] = 5
ordered['date'] = 1
print("Insertion order preserved:")
for key, value in …
Check Invertible Mapping for Duplicate Values in Python
Detect duplicate values among (key, value) pairs to ensure the mapping is invertible, using a dictionary for O(1) lookups.
def invertible_after_dedup(pairs):
"""
Check whether a set of (key, value) pairs is invertible,
i.e., no duplicate values exist for different keys.
"""
seen = {}
for key, value in pairs:
if value in seen and seen[value] != key:
return False, f"Duplicate value '{value}' for k…
Compare Two Dictionaries in Python
Compare two dictionaries by finding common keys, unique keys, and value differences using Python's set operations.
def compare_data(dict1, dict2):
"""Compare two dictionaries and summarize similarities/differences."""
keys1 = set(dict1.keys())
keys2 = set(dict2.keys())
common_keys = keys1 & keys2
only_in_first = keys1 - keys2
only_in_second = keys2 - keys1
print(f"Common keys ({len(common_keys…
OOP & classes
Classes, instances, methods, dataclasses, and object-oriented design in Python.
Add property getter setter validation in Python
Shows how to use @property with a setter to validate values before assigning them in a Python class.
class Temperature:
def __init__(self, celsius=0):
self._celsius = celsius # Use underscore to avoid recursion
@property
def celsius(self):
"""Getter returns the stored value."""
return self._celsius
@celsius.setter
def celsius(self, value):
"""Setter valid…
Binary Tree Inorder Traversal in Python
Define a TreeNode class and recursively print in-order traversal (left, node, right) of a binary tree.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def inorder_traversal(root):
return inorder_traversal(root.left) + [root.val] + inorder_traversal(root.right) if root else []
if __name__ == "__main__":
# Build a…
Borg pattern shared state in Python
Implement the Borg pattern to share state across class instances by assigning a class-level dictionary to each instance's __dict__.
class Borg:
_shared_state = {}
def __init__(self):
self.__dict__ = Borg._shared_state
class ConfigManager(Borg):
def __init__(self):
super().__init__()
if not hasattr(self, "settings"):
self.settings = {}
def set(self, key, value):
self.settings[key] = va…
Bridge Pattern in Python: Separate Abstraction from Implementation
Implement the Bridge design pattern in Python so that an abstraction (remote control) can operate on different device implementations independently.
class RemoteControl:
"""Abstraction: controls a device without knowing implementation details."""
def __init__(self, device):
self.device = device
def toggle_power(self):
if self.device.is_enabled():
self.device.disable()
return "Power off"
else:
…
Composable Predicates with the &, |, ~ Operators in Python
Define a reusable Predicate class that combines boolean checks with & (AND), | (OR), and ~ (NOT) operators.
class Predicate:
def __init__(self, func, name=None):
self.func = func
self.name = name or getattr(func, "__name__", "predicate")
def __call__(self, value):
return self.func(value)
def __and__(self, other):
return Predicate(lambda v: self(v) and other(v), f"({self.name} AN…
Composition over Inheritance: How to Build a Wallet Account in Python
Demonstrates composition by wrapping a WalletAccount class in an AuditedWallet decorator-like class to add behavior without changing the original class.
class WalletAccount:
def __init__(self, owner, balance=0.0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("Deposit must be positive")
self.balance += amount
return self.balance
def withdraw(self, …
Algorithms & data structures
Classic patterns — search, sort, stacks, queues, and practical complexity-aware code.
Binary Search for Ship Capacity in Python
Use binary search to find the minimum ship capacity that can transport all packages within a given number of days.
def ship_within_days(weights, days):
def can_ship(capacity):
current = 0
needed_days = 1
for weight in weights:
if current + weight > capacity:
needed_days += 1
current = 0
current += weight
return needed_days <= days
low …
Binary Search on Answer in Python: Koko Eating Bananas
Find the minimum eating speed so Koko finishes all banana piles within a given hour limit using binary search on the answer.
import math
def min_eating_speed(piles, h):
"""Return minimum integer eating speed K so Koko finishes within h hours."""
def hours_needed(speed):
return sum(math.ceil(p / speed) for p in piles)
low, high = 1, max(piles)
while low < high:
mid = (low + high) // 2
if hours_needed…
Bucket Numbers into Histogram Bin Counts in Python
Partition a list of numbers into equal-width histogram bins and count how many fall into each bin using only the Python standard library.
from collections import Counter
def histogram_bins(numbers, num_bins):
"""Bucket numbers into histogram bin counts."""
if not numbers:
return []
min_val = min(numbers)
max_val = max(numbers)
bin_width = (max_val - min_val) / num_bins
# Handle edge case where all values are id…
Container With Most Water: Two-Pointer Solution in Python
Find the maximum water a container can hold from a list of heights using an efficient two-pointer technique in O(n) time.
from typing import List
def max_water_container(heights: List[int]) -> int:
left, right = 0, len(heights) - 1
max_area = 0
while left < right:
width = right - left
height = min(heights[left], heights[right])
area = width * height
max_area = max(max_area, area)
…
Count Smaller Elements to the Right in Python
Return a list where each index counts how many elements to its right are smaller than that element using a clean O(n²) nested-loop approach.
def count_smaller_elements(arr):
"""
Return a list where result[i] is the number of elements
to the right of arr[i] that are smaller than arr[i].
"""
result = []
for i in range(len(arr)):
count = 0
for j in range(i + 1, len(arr)):
if arr[j] < arr[i]:
…
Depth First Search Traversal Order in Python
Recursive depth-first search that returns the visit order of nodes in an adjacency list graph starting from a given node.
def dfs_order(adj, start):
visited = set()
order = []
def dfs(node):
visited.add(node)
order.append(node)
for neighbor in adj.get(node, []):
if neighbor not in visited:
dfs(neighbor)
dfs(start)
return order
if __name__ == "__main__":
# Dem…
Comprehensions & generators
List/dict/set comprehensions, generator expressions, and lazy iteration.
Batch Rows in Chunks with a Generator in Python
Group a list of row dicts into fixed-size chunks using a generator that yields one slice per call.
from typing import Iterator, List
def batch_rows(rows: List[dict], batch_size: int) -> Iterator[List[dict]]:
for i in range(0, len(rows), batch_size):
yield rows[i:i + batch_size]
if __name__ == "__main__":
sample_rows = [
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"},
…
Build a Generator Pipeline in Python: Filter Then Map
Create a lazy data pipeline by chaining generator functions that read, filter, map, and write data step by step.
def read_data():
return ["a", "bb", "ccc", "dd", "eeeee", "f"]
def filter_short(words):
return (word for word in words if len(word) >= 2)
def map_to_upper(words):
return (word.upper() for word in words)
def write_data(words):
for word in words:
print(word)
if __name__ == "__main__":
…
Build a lazy generator to read file lines in Python
Create a generator function that yields file lines one at a time, avoiding loading the entire file into memory, and demonstrate its lazy processing.
def lazy_lines(filepath):
"""Yield lines from a file one at a time without loading the whole file into memory."""
with open(filepath, 'r', encoding='utf-8') as file:
for line in file:
yield line.rstrip('\n')
if __name__ == "__main__":
# Create a sample file to demonstrate
sample_c…
Chunk an Iterable into Batches with a Generator in Python
Yield fixed-size batches from any iterable lazily using itertools.islice inside a generator function.
from itertools import islice
def chunked(iterable, size):
iterator = iter(iterable)
while True:
batch = list(islice(iterator, size))
if not batch:
break
yield batch
if __name__ == "__main__":
data = range(10)
for batch in chunked(data, 3):
print(batch)
Convert Data in Python with Comprehensions and Generators
Convert mixed data to integers, filter and transform numbers, and extract fields from dicts using list comprehensions and generator expressions.
def convert_numbers(data):
"""Convert a list of mixed values into integers using a comprehension."""
return [int(item) for item in data if item is not None]
def double_even_numbers(numbers):
"""Double only even numbers using a generator expression."""
return (n * 2 for n in numbers if n % 2 == 0)
d…
Count Data in Python with Comprehensions and Generators
Count list items with a dict comprehension and generate squares lazily with a generator expression, printing both results.
from collections import Counter
data = ["apple", "banana", "apple", "cherry", "banana", "apple"]
counts = {item: data.count(item) for item in set(data)}
square_gen = (x * x for x in range(5))
squares = list(square_gen)
if __name__ == "__main__":
print("Manual count:", counts)
print("Counter:", dict(Counter…
AI & LLM integration patterns
Call LLM APIs, structure prompts, parse responses, and ship AI features safely.
Cache LLM Completions by Hashing the Prompt in Python
A simple in-memory cache that stores LLM completions keyed by a SHA-256 hash of the prompt to avoid recomputing identical requests.
import hashlib
import json
class PromptCache:
def __init__(self):
self.cache = {}
def _hash_prompt(self, prompt: str) -> str:
return hashlib.sha256(prompt.encode("utf-8")).hexdigest()
def get(self, prompt: str) -> str | None:
key = self._hash_prompt(prompt)
return self.ca…
Chain of Thought Prompting in Python: Step-by-Step Reasoning Demo
This demo shows how to structure a function that explains its own reasoning step-by-step, mimicking chain-of-thought prompting for AI systems.
def solve_math_step_by_step(expression: str) -> str:
"""Solves a simple expression, showing each reasoning step."""
# Step 1: Parse the expression (assume "a + b" or "a - b")
parts = expression.split()
a = int(parts[0])
op = parts[1]
b = int(parts[2])
steps = []
steps.append(f"Step…
Circuit Breaker Pattern in Python for LLM API Calls
Implements a circuit breaker class that wraps LLM client calls to fail fast when the service is degrading, then recover automatically after a timeout.
import time
class CircuitBreaker:
def __init__(self, failure_threshold=3, recovery_timeout=5):
self.failure_threshold = failure_threshold
self.recovery_timeout = recovery_timeout
self.failure_count = 0
self.state = "closed"
self.last_failure_time = None
def call(self, …
Cosine Similarity to Retrieve Top K Chunks in Python
Compute cosine similarity between a query vector and a list of chunk vectors, then return the indices and scores of the top k most similar chunks.
import numpy as np
from numpy.linalg import norm
def cosine_similarity(vec1, vec2):
return np.dot(vec1, vec2) / (norm(vec1) * norm(vec2))
def retrieve_top_k(query_vec, chunk_vectors, k=3):
similarities = [cosine_similarity(query_vec, vec) for vec in chunk_vectors]
top_indices = sorted(range(len(similarit…
Demonstrate Prompt Injection Bypass in Python
Simulate why naive system prompt filters fail against prompt injection with casing and spacing variations.
# Demonstrate why system prompts can be bypassed by simulated user input
# This demo shows a naive filter being ignored via prompt injection
def process_user_message(message, system_rules):
"""Simulate an AI that follows system rules but gets tricked."""
# Claim to check system rules
for rule in system_ru…
How to Accumulate Streamed Tokens into a Final String in Python
Accumulate a stream of tokens into a single final string by concatenating each token in sequence.
def accumulate_tokens(tokens):
"""Accumulate a stream of tokens into a single final string."""
result = ""
for token in tokens:
result += token
return result
if __name__ == "__main__":
token_stream = ["Hello", ", ", "world", "!", " This ", "is ", "accumulated."]
final_string = accumul…
Automation & scripting
CLI tools, scheduled jobs, filesystem tasks, and glue scripts that save time.
Aggregate Log Errors Count by Hour in Python
Counts ERROR log lines per hour using regex and Counter, returning a sorted dictionary of hourly totals.
import re
from collections import Counter
from datetime import datetime
def aggregate_errors_by_hour(log_lines):
pattern = re.compile(r'^(\d{4}-\d{2}-\d{2} \d{2}):\d{2}:\d{2}.*ERROR')
hourly_counts = Counter()
for line in log_lines:
match = pattern.match(line)
if match:
ho…
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",
…
Automatically Clean Temporary Files from Applications Using Python
A Python script that safely deletes temporary files from common application temp directories across Windows, Linux, and macOS, tracking cleaned count and disk space.
import os
import shutil
import tempfile
import platform
def clean_application_temp_files():
"""Delete common temporary file locations safely."""
system = platform.system()
temp_dirs = []
if system == "Windows":
temp_dirs.extend([
os.path.join(os.getenv("LOCALAPPDATA"), "Temp"),
…
Automatically Download the Latest Software Release from GitHub with Python
Use the GitHub API to fetch the latest release metadata and download the first asset (binary or archive) to a local directory.
import requests
import sys
from pathlib import Path
def download_latest_release(owner: str, repo: str, output_dir: str = ".") -> None:
"""Download the latest release asset from a GitHub repository."""
url = f"https://api.github.com/repos/{owner}/{repo}/releases/latest"
response = requests.get(url)
res…
Automatically Generate Charts from CSV Files with One Command
Read a CSV file with headers, extract the first two numeric columns, and save a matplotlib line chart as a PNG image.
import csv
import sys
from pathlib import Path
import matplotlib.pyplot as plt
def generate_chart(csv_path: str) -> None:
"""Read a CSV file with headers and plot the first two numeric columns."""
data = []
with open(csv_path, 'r', newline='') as f:
reader = csv.reader(f)
headers = next(re…
Automatically Generate Hardware Inventory Reports in Python
Generate a system hardware report including OS version, CPU cores, RAM, and disk usage using platform and psutil.
import platform
import psutil # requires: pip install psutil
from datetime import datetime
def generate_hardware_report():
report_lines = []
report_lines.append(f"Report Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
report_lines.append(f"System: {platform.system()} {platform.release()} ({pl…
Data pipelines & processing
ETL-style flows, batch transforms, validation, and moving data between formats.
Add a UUID Surrogate Key to Each Row in a CSV with Python
Generate a unique UUID string for every row in a CSV file using the standard-library uuid and csv modules.
import uuid
import csv
def add_surrogate_key(filename):
with open(filename, newline='') as f_in:
reader = csv.DictReader(f_in)
rows = list(reader)
for row in rows:
row['surrogate_key'] = str(uuid.uuid4())
with open(filename, 'w', newline='') as f_out:
writer = csv.DictWri…
Attach Source File Metadata to Records in Python
Add a source filename field to each record in a list by merging a new key into every dictionary using a dict unpacking comprehension.
from pathlib import Path
import json
def attach_source_metadata(records, source_file):
"""Attach source filename metadata to each record."""
return [
{**record, "source": Path(source_file).name}
for record in records
]
if __name__ == "__main__":
source = "/data/raw/customers.csv"
…
Build a Python Utility That Detects Duplicate Records Across Multiple Excel Sheets
A Python utility that uses pandas to find overlapping records across different Excel sheets based on specified key columns.
import pandas as pd
from pathlib import Path
def find_duplicate_records_across_sheets(file_path: str, key_columns: list, sheet_names: list) -> dict:
"""
Detect duplicate records across multiple Excel sheets based on specified key columns.
Args:
file_path: Path to the Excel file
key_co…
Check Null Rate Threshold in PySpark DataFrame
This PySpark code checks the null rate of specified DataFrame columns against a threshold and returns violations.
from pyspark.sql import SparkSession
from pyspark.sql.functions import col, sum, count
def check_null_rate(df, threshold=0.2, columns=None):
"""
Check null rate for specified columns (or all) against a threshold.
Returns columns that exceed the threshold.
"""
cols = columns or df.columns
total…
Count Records Processed per Category in Python
Use a Counter dictionary to track how many records of each type (ok, error, retry) were processed in a data pipeline.
from collections import Counter
import random
processed_counter = Counter()
def process_records(records):
for record in records:
processed_counter[record] += 1
return len(records)
if __name__ == "__main__":
sample_records = [random.choice(["ok", "error", "retry"]) for _ in range(10)]
print(f…
Create Data Helper Functions in Python for Beginners
Build reusable Python helper functions to load, filter, sort, summarize, and save JSON data — a beginner-friendly starting point for small data pipelines.
import json
from pathlib import Path
from typing import Any, Dict, List
def load_json_file(filepath: str) -> Dict[str, Any]:
"""Load JSON data from a file."""
with Path(filepath).open("r", encoding="utf-8") as file:
return json.load(file)
def filter_by_key(
data: List[Dict[str, Any]], key: str,…
Git + Python
Automate Git from Python — diffs, hooks, release tags, and repo housekeeping.
Amend Last Commit Message in Python
This script uses subprocess to run `git commit --amend` and update the most recent commit's message in your repository.
import subprocess
import sys
def amend_last_commit_message(new_message: str) -> None:
"""Change the message of the most recent commit."""
result = subprocess.run(
["git", "commit", "--amend", "-m", new_message],
capture_output=True,
text=True,
check=False,
)
if result.…
Bisect Good Bad Automation Script in Python
This Python script implements a binary search to find the first bad version in a list, simulating an automation script for git bisect.
import bisect
def find_first_bad(versions):
"""Given a list of version objects with .is_bad(), find first bad version."""
lo, hi = 0, len(versions)
while lo < hi:
mid = (lo + hi) // 2
if versions[mid].is_bad():
hi = mid
else:
lo = mid + 1
return lo
clas…
Build a Simple Log Graph in Python
Create a basic one-dimensional bar chart from log lines by counting occurrences of leading numeric keys.
import heapq
def log_graph(log_lines: list[str]) -> str:
"""Build a simple per-line, one-dimensional visual graph from log entries."""
counts: dict[int, int] = {}
for line in log_lines:
tokens = line.split()
if tokens:
try:
idx = int(tokens[0])
exce…
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.
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…
Count Unique Contributors from Git Shortlog in Python
Parses git shortlog -sn output to count the number of unique contributors, handling duplicate entries and variable whitespace.
import subprocess
from collections import Counter
# Mock shortlog output as a list of lines (simulating git shortlog -sn output)
MOCK_SHORTLOG = """ 120 Alice Johnson
88 Bob Smith
45 Alice Johnson
30 Carol Williams
25 Bob Smith
10 Dave Brown
"""
def count_contributors_from_shortlog(text):
"…
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.
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…
Cloud + Python
Cloud SDK patterns — storage, serverless handlers, secrets, and deployment helpers.
Build a URL Shortener Client with Python
A Python class that shortens long URLs and resolves short codes using a REST API built with requests.
import json
import sys
import requests
class URLShortenerClient:
def __init__(self, base_url="http://tinyurl.com"):
self.base_url = base_url
def shorten_url(self, long_url):
payload = {"url": long_url}
headers = {"Content-Type": "application/json"}
response = requests.post(f"{…
Create a Cloud Storage Helper Class in Python
Build a simple local file-based helper class that mimics cloud storage operations like save, load, and list JSON objects.
import datetime
import json
from pathlib import Path
class CloudDataHelper:
"""Simple helper for reading/writing JSON files in a cloud-style folder."""
def __init__(self, base_dir: str = "cloud_storage"):
self.base_dir = Path(base_dir)
self.base_dir.mkdir(exist_ok=True)
def save_json(se…
Create a Data Helper Class for Beginners in Python
A simple Python class to read and write JSON and CSV files from a local directory, ideal for automating data workflows in cloud environments.
import json
from pathlib import Path
class DataHelper:
"""Simple helper for reading and writing common data files."""
def __init__(self, directory="data"):
self.directory = Path(directory)
self.directory.mkdir(exist_ok=True)
def save_json(self, filename, data):
filepath =…
Cross Account Role Chaining Mock Credentials in Python
Simulate AWS STS AssumeRole with mock credentials for cross-account role chaining in Python.
import json
class CredentialChain:
def __init__(self, account_id, role_name):
self.account_id = account_id
self.role_name = role_name
self.credentials = {}
def assume_role(self, session_name="mock_session"):
"""Simulate STS AssumeRole, returning mock credentials with expiry.""…
Exponential Backoff with Jitter for Cloud API Calls in Python
A Python snippet demonstrating exponential backoff with jitter for retrying transient cloud API failures, using a simulated client that has a configurable success rate.
import random
import time
def exponential_backoff_with_jitter(retries=5, base_delay=0.5, max_delay=4.0, jitter_factor=0.3):
for attempt in range(1, retries + 1):
delay = min(max_delay, base_delay * (2 ** (attempt - 1)))
jitter = delay * random.uniform(-jitter_factor, jitter_factor)
effect…
Generate Mock CloudFormation Stack Events in Python
Generate a list of mock AWS CloudFormation stack events with random resources, statuses, and timestamps, and print them as JSON.
import json
import random
from datetime import datetime, timedelta
def generate_mock_stack_events(stack_name="MyTestStack", num_events=10):
"""Generate a list of mock CloudFormation stack events."""
resources = [
("AWS::S3::Bucket", "MyBucket"),
("AWS::EC2::Instance", "MyInstance"),
("…
Modern tooling
uv, ruff, pyproject.toml, packaging, and current Python project workflows.
Build a Recipe Runner Mock in Python
A Python script that mocks a command runner recipe system: maps recipe names to shell commands, executes them with subprocess, and prints the output and exit code.
import subprocess
import sys
def run_recipe(recipe: str) -> None:
"""Simulate a command runner recipe by printing the command and exit code."""
print(f"Running recipe: {recipe}")
result = subprocess.run(recipe, shell=True, capture_output=True, text=True)
print(f"Exit code: {result.returncode}")
i…
Build a Textual TUI App Skeleton in Python
Create a minimal Textual terminal UI app with a header, label, button, and footer, ready for interactive mock demonstrations.
from textual.app import App, ComposeResult
from textual.widgets import Header, Footer, Button, Label
class MockApp(App):
"""A minimal Textual TUI app skeleton."""
BINDINGS = [("q", "quit", "Quit")]
def compose(self) -> ComposeResult:
"""Create child widgets."""
yield Header()
yie…
Configure ruff linter rules in pyproject.toml with Python
Reads an existing pyproject.toml and merges common ruff linter rules into the tool.ruff section using Python's tomllib.
import tomllib
from pathlib import Path
def configure_ruff_linter_rules(project_path: str = ".") -> dict:
"""Add common ruff linter rules to pyproject.toml if missing."""
pyproject_path = Path(project_path) / "pyproject.toml"
# Default config for ruff linter with practical rules
ruff_config = {
…
Data Conversion Helper Functions in Python
A set of beginner-friendly helper functions to convert between JSON strings and Python data, parse dates, and read/write files using pathlib.
from datetime import datetime
from pathlib import Path
import json
def to_json(data, indent=2):
"""Convert Python data to pretty-printed JSON string."""
return json.dumps(data, indent=indent, default=str)
def from_json(json_string):
"""Parse JSON string back into Python data."""
return json.loads(jso…
How to Bind and Mock structlog Context in Python
Shows how to bind persistent key-value context to a structlog logger, unbind keys, and mock the logger in tests to verify context is passed correctly.
import structlog
from unittest.mock import patch
logger = structlog.get_logger()
def demo():
logger = structlog.get_logger()
logger = logger.bind(user_id=42, request_id="abc123")
logger.info("user logged in", action="login")
# Unbind a key
logger = logger.unbind("user_id")
logger.info("r…
How to Build a Chainable Filter Helper in Python
A beginner-friendly dataclass helper that chains filters, uniqueness, and slicing on any sequence, returning a plain list at the end.
from dataclasses import dataclass
from typing import Callable, Iterator, Sequence, TypeVar
T = TypeVar("T")
@dataclass
class FilterAssistant:
"""Beginner-friendly helper to filter any collection."""
data: Sequence[T]
def where(self, predicate: Callable[[T], bool]) -> "FilterAssistant":
return …
Concurrency & performance
asyncio, threading, multiprocessing, and profiling-friendly performance patterns.
Benchmark list.append vs deque.append in Python
Measures and compares the performance of appending to a Python list versus a collections.deque using timeit.repeat, showing best and average timings.
"""Benchmark list.append vs collections.deque.append."""
import timeit
def bench(stmt, setup, repeat=5, number=1_000_000):
times = timeit.repeat(stmt, setup=setup, repeat=repeat, number=number)
return min(times), sum(times) / len(times)
if __name__ == "__main__":
number = 1_000_000
list_best, list_a…
Build a Python Performance Profiler That Generates Readable Reports
Use cProfile and pstats to profile Python functions and print a sorted performance report showing the top time-consuming calls.
import cProfile
import pstats
import io
from pathlib import Path
def slow_function():
total = 0
for i in range(500_000):
total += i ** 2
return total
def fast_function():
total = sum(i * i for i in range(500_000))
return total
def profile_functions():
profiler = cProfile.Profile()
…
Graceful Shutdown Executor Context Manager in Python
A context manager that starts a background thread and ensures it stops gracefully on exit, handling timeouts and exceptions.
import signal
import threading
import time
from contextlib import contextmanager
@contextmanager
def graceful_shutdown_executor(timeout=5.0):
"""Context manager that runs a task and gracefully stops it on timeout or exception."""
stop_event = threading.Event()
def task():
print("Task started")
…
How to Build a Producer-Consumer Pattern with asyncio.Queue in Python
This code implements a classic producer-consumer pattern using asyncio.Queue to coordinate one producer task that generates items and two consumer tasks that process them concurrently, with a sentinel value to signal completion.
import asyncio
import random
async def producer(queue, item_count):
for i in range(item_count):
item = random.randint(1, 100)
await queue.put(item)
print(f"Produced: {item}")
await asyncio.sleep(0.1)
await queue.put(None) # Sentinel to signal end
async def consumer(queue, n…
How to Cancel an asyncio Task with Graceful Cleanup in Python
Cancel a running asyncio task, handle the cancellation signal inside a worker coroutine to perform cleanup, then re-raise so the cancellation propagates correctly.
import asyncio
async def worker(name: str, sleep: float) -> None:
try:
print(f"{name}: starting")
await asyncio.sleep(sleep)
print(f"{name}: completed")
except asyncio.CancelledError:
print(f"{name}: cancelled, cleaning up...")
await asyncio.sleep(0.2) # Simulate clea…
How to Convert Data in Parallel with ThreadPoolExecutor in Python
This example demonstrates converting a list of items in parallel using ThreadPoolExecutor, showing performance gains over serial processing.
import time
from concurrent.futures import ThreadPoolExecutor
def convert_data(item):
"""Simulate a CPU/IO-bound conversion task."""
time.sleep(0.05) # simulate work
return item.upper()
if __name__ == "__main__":
items = [f"item_{i}" for i in range(20)]
start = time.perf_counter()
serial_…
Testing & modern typing
pytest basics, mocks, type hints, TypedDict, Protocol, and static-checking patterns.
Capture stdout and stderr with pytest capsys
Use pytest's capsys fixture to capture and assert on standard output and error streams in your tests.
import pytest
# Function under test
def greet(name):
print(f"Hello, {name}!")
print(f"Error: {name} not found", file=sys.stderr)
def test_captures_stdout_and_stderr(capsys):
greet("Alice")
captured = capsys.readouterr()
assert "Hello, Alice!" in captured.out
assert "Error: Alice not foun…
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:
…
Dataclass with Type Hints Fields in Python
Create a data class with typed fields and default values, then instantiate and inspect it.
from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int
email: str = "unknown@example.com"
is_active: bool = True
if __name__ == "__main__":
person = Person(name="Alice", age=30)
print(person)
print(f"Name: {person.name}, Age: {person.age}, Email: {person.email}, A…
Dependency Injection in Python for Testability
Inject a config dependency into a service so you can swap a real environment-based config for a fake one in tests.
import os
class Config:
"""Simple config loader that can be easily faked in tests."""
def get(self, key, default=None):
return os.environ.get(key, default)
class UserService:
def __init__(self, config):
self.config = config
def get_timeout(self):
return int(self.config.get(…
Design Data Helpers with Python TypedDict and Literal
Use TypedDict, Literal, and Union to define typed data shapes and parse values in Python.
from typing import TypedDict, Literal, Optional, Union, List
class User(TypedDict):
name: str
age: int
role: Literal["admin", "user", "guest"]
def describeUser(data: User) -> str:
return f"{data['name']} ({data['age']}) — {data['role']}"
def parse_value(item: Union[int, str, None]) -> str:
if it…
Fix and Test a Regression Bug in Python with Unit Tests
This code implements a circle area function that raises ValueError for negative radii, then runs basic tests and a regression check for that edge case.
import math
def calculate_area(radius):
"""Calculate the area of a circle given its radius."""
if radius < 0:
raise ValueError("Radius cannot be negative")
return math.pi * radius ** 2
def main():
test_cases = [0, 1, 2.5, 5, 10]
print("Circle Area Calculator")
print("-" * 30)
…
System design patterns
Sharding, load balancing, CAP tradeoffs, and scaling patterns — interview and production ready.
Build a BFF (Backend for Frontend) Mock Aggregator in Python
A minimal HTTP server implementing the BFF pattern that aggregates user data and orders from two mock backends into a single JSON response.
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse
class MockBackendA:
def get_user(self, user_id):
return {"id": user_id, "name": "Alice", "service": "backend-a"}
class MockBackendB:
def get_orders(self, user_id):
return [
{…
Builder pattern for mocking complex objects in Python
Use a fluent Builder to construct realistic mock objects with defaults, enabling readable test data setup.
class User:
def __init__(self):
self.name = "default"
self.age = 0
self.email = "unknown@example.com"
self.address = "unknown"
def __repr__(self):
return f"User(name={self.name!r}, age={self.age}, email={self.email!r}, address={self.address!r})"
class UserBuilder:
…
Circuit Breaker Pattern in Python: Closed, Open, and Half-Open States
Implement a circuit breaker with closed, open, and half-open states to prevent repeated calls to failing services and allow recovery after a timeout.
class CircuitBreaker:
def __init__(self, failure_threshold=3, timeout_seconds=5):
self.failure_threshold = failure_threshold
self.timeout_seconds = timeout_seconds
self.state = "closed"
self.failure_count = 0
self.last_failure_time = None
def record_success(self):
…
Create a Data Helper Class in Python
A reusable DataHelper class that saves and loads JSON and CSV files from a configurable base directory, with automatic header detection for CSV.
import json
import csv
from pathlib import Path
class DataHelper:
def __init__(self, base_path="."):
self.base_path = Path(base_path)
self.base_path.mkdir(exist_ok=True)
def save_json(self, data, filename):
path = self.base_path / filename
with open(path, "w") as f:
…
Domain Driven Design Aggregate Root Example in Python
Model an Order as an aggregate root with invariants enforced through methods, demonstrating DDD principles in Python.
from __future__ import annotations
from dataclasses import dataclass
from typing import List, Optional
from uuid import uuid4
class Money:
def __init__(self, amount: float, currency: str = "USD"):
self.amount = amount
self.currency = currency
def __add__(self, other: Money) -> Money:
…
Facade Pattern in Python with Mock Simplification
This code demonstrates the Facade pattern by hiding complex subsystem interactions behind a simple start/stop interface, and adds a MockFacade for testing failure scenarios.
class SubsystemA:
def operation_a(self):
return "Subsystem A: ready"
class SubsystemB:
def operation_b(self):
return "Subsystem B: ready"
class SubsystemC:
def operation_c(self):
return "Subsystem C: ready"
class Facade:
def __init__(self):
self._a = SubsystemA()
…
API design & gRPC
REST best practices, protobuf, API versioning, and backward-compatible service contracts.
Build a Bulk Array POST Mock Server in Python
Creates an HTTP mock server that accepts POST requests with a JSON array and returns incremental IDs for each item.
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse
class MockHandler(BaseHTTPRequestHandler):
def do_POST(self):
if urlparse(self.path).path != "/bulk":
self.send_response(404)
self.end_headers()
return
cont…
Build a Mock REST API with PUT and GET in Python
A minimal mock REST server implementing idempotent PUT for resource replacement and GET for retrieval, built with Python's http.server module.
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
from urllib.parse import urlparse
mock_db = {}
class MockAPIHandler(BaseHTTPRequestHandler):
def do_PUT(self):
parsed = urlparse(self.path)
resource_id = parsed.path.strip("/").split("/")[-1]
content_length = int(self.…
Convert Protobuf to JSON and Dict in Python
Provides static helper methods to convert between protobuf messages, JSON strings, and Python dictionaries using the google.protobuf library.
from google.protobuf.json_format import MessageToJson, Parse
import json
class DataConverter:
"""Helper class to convert between protobuf messages and common formats."""
@staticmethod
def to_json(message, indent=2):
"""Convert a protobuf message to JSON string."""
return MessageToJson(me…
Create a Data Helper in Python for gRPC-style APIs
This code builds a simple DataHelper class that mimics gRPC request/response handling with in-memory storage, JSON serialization, and basic CRUD operations for beginners.
import json
from dataclasses import dataclass, asdict
from typing import Dict, Any
@dataclass
class User:
user_id: int
name: str
email: str
class DataHelper:
"""Simple helper to demonstrate gRPC-like data handling for beginners."""
def __init__(self) -> None:
self._users: Dict[int, Use…
Format data in Python using dataclasses like gRPC messages
Convert Python dataclasses to and from dicts and format them gRPC-style for clean data handling.
from dataclasses import dataclass
from typing import Any, Dict, List, Optional
@dataclass
class ProductInfo:
"""Data class representing a gRPC-style product message."""
name: str
price: float
tags: List[str]
description: Optional[str] = None
def to_dict(self) -> Dict[str, Any]:
"""C…
Generate an OpenAPI Spec from Mock Routes in Python
This Python script generates an OpenAPI 3.0 specification from a simple mock routes dictionary, mapping each HTTP method to response examples.
import json
from pathlib import Path
def generate_openapi_spec(routes: dict, title: str = "Mock API", version: str = "1.0.0") -> dict:
paths = {}
for route, methods in routes.items():
path_item = {}
for method, response_data in methods.items():
method = method.lower()
…
Streaming & messaging
Kafka-style pub/sub, event consumers, async pipelines, and message-driven workflows.
At Most Once Fire-and-Forget Mock in Python
A Python mock that enforces send() is called at most once and records the arguments for verification.
class FireForgetMock:
def __init__(self):
self._calls = 0
self._last_args = None
self._last_kwargs = None
def send(self, *args, **kwargs):
if self._calls > 0:
raise RuntimeError("send() called more than once")
self._calls += 1
self._last_args = args
…
Batch Consume Process Commit Pattern in Python
A mock batch processor that accumulates items in a queue, processes full batches, commits successful or failed results, and flushes remaining items.
import random
import threading
import time
from collections import deque
class MockBatchProcessor:
def __init__(self, process_func, commit_func, batch_size=5):
self.queue = deque()
self.batch_size = batch_size
self.process_func = process_func
self.commit_func = commit_func
de…
Build a Streaming Messaging Helper in Python
Create a simple message stream class that stores recent messages, sends user messages, and retrieves history or latest messages with timestamps.
from collections import deque
from dataclasses import dataclass
from datetime import datetime
import time
@dataclass
class Message:
user: str
text: str
timestamp: str = ""
def __post_init__(self):
if not self.timestamp:
self.timestamp = datetime.now().strftime("%H:%M:%S")
class…
Dead Letter Queue Failed Messages List Mock in Python
Implements a simple in-memory dead letter queue to collect, list, and retry failed messages, with JSON serialization for inspection in streaming pipelines.
import json
from collections import deque
class Message:
def __init__(self, message_id, payload, attempts=0):
self.message_id = message_id
self.payload = payload
self.attempts = attempts
def __repr__(self):
return f"Message(id={self.message_id}, attempts={self.attempts})"
c…
Dedupe processed message IDs in Python
Filters an inbox of messages by removing items whose IDs have already been processed, using a set for fast lookups.
from pathlib import Path
import json
def dedupe_processed_ids(inbox_file: Path, processed_file: Path) -> list:
processed = set(json.loads(processed_file.read_text()))
inbox = json.loads(inbox_file.read_text())
deduped = [item for item in inbox if item["id"] not in processed]
return deduped
if __nam…
Event Envelope with Schema Version Field in Python
Build a typed event envelope dataclass with an explicit schema version field for mock streaming scenarios.
from dataclasses import dataclass, field
from datetime import datetime
import uuid
@dataclass
class Event:
event_id: str = field(default_factory=lambda: str(uuid.uuid4()))
event_type: str = "user.created"
version: str = "1.0.0"
created_at: str = field(default_factory=lambda: datetime.utcnow().isoform…
Caching & Redis
Cache-aside, TTL, invalidation, hot keys, and in-memory lookup patterns at scale.
Cache Asides in Python with a Read-Through Loader
Implements a cache-aside pattern with a read-through loader that fetches missing keys from a backing data store and caches them.
class DataStore:
"""Mock database with a few records."""
def __init__(self):
self.data = {1: "Alice", 2: "Bob", 3: "Charlie"}
def get(self, key):
print(f"Loading key {key} from database")
return self.data.get(key)
class CacheAsideLoader:
"""Cache-aside pattern with a read-thr…
Cache Data in Redis with Python
A beginner-friendly Redis cache helper that stores JSON strings with a TTL and retrieves them with the redis-py client.
import redis
class DataCache:
def __init__(self, host="localhost", port=6379, db=0):
self.client = redis.Redis(host=host, port=port, db=db, decode_responses=True)
def cache_data(self, key, value, ttl=60):
self.client.setex(key, ttl, value)
def get_cached_data(self, key):
return …
Cache Penetration Null Object Mock in Python
Implement a cache that stores a null marker on misses to prevent repeated database hits, reducing cache penetration.
import time
from collections import defaultdict
from typing import Any, Optional
class Cache:
def __init__(self):
self.store: dict[str, Any] = {}
self.ttl: dict[str, float] = {}
self.null_marker = object()
def get(self, key: str, ttl: int = 60, fallback:
Any = None) -> An…
Cache Stampede Prevention with SingleFlight in Python
Implements a SingleFlight pattern in Python to deduplicate concurrent cache-miss computations and prevent cache stampede.
import threading
import time
from functools import wraps
class SingleFlight:
def __init__(self):
self._lock = threading.Lock()
self._inflight = None
def do(self, key, fn):
with self._lock:
if self._inflight is not None:
return self._inflight[1]
…
Cache Warming with Python: Preload Hot Keys
Demonstrates a simple LRU-like cache with a warm method that preloads hot keys with mock values using OrderedDict.
import time
from collections import OrderedDict
class CacheWarm:
def __init__(self, capacity=3):
self.capacity = capacity
self.cache = OrderedDict()
self.hot_keys = []
def warm(self, keys):
"""Preload hot keys into cache with mock values."""
for key in keys:
…
Coalescing duplicate in-flight requests: one shared result for concurrent callers
Runs identical concurrent requests through a single shared call, caching the result while it's in flight and returning the same value to all callers.
import time
import threading
from collections import defaultdict
class CoalescingExecutor:
def __init__(self):
self._locks = defaultdict(threading.Lock)
self._in_flight = {}
def execute(self, key, func):
with self._locks[key]:
if key in self._in_flight:
re…
Reliability & rate limiting
Retries, exponential backoff, circuit breakers, token buckets, and idempotent handlers.
At Least Once with Idempotent Consumer in Python
Implements a thread-safe idempotent consumer that processes each unique message exactly once, even when a producer sends duplicates under an at-least-once delivery model.
import threading
import time
import uuid
from collections import Counter
class IdempotentConsumer:
def __init__(self):
self.processed = set()
self._lock = threading.Lock()
def consume(self, message_id, payload):
with self._lock:
if message_id in self.processed:
…
Build a Rate Limiter Decorator in Python
This code defines a reusable rate limiter decorator that caps function calls within a sliding time window using a deque and monotonic time.
import time
from collections import deque
def rate_limiter(max_calls: int, period: float):
calls = deque()
def decorator(func):
def wrapper(*args, **kwargs):
now = time.monotonic()
while calls and now - calls[0] >= period:
calls.popleft()
if len(ca…
Build a queue-based admission control system in Python
Implement a simple bounded-queue admission controller that accepts or rejects incoming requests based on current queue capacity.
from collections import deque
import time
class AdmissionControl:
"""Simple admission control using a bounded queue.
Requests arrive at the queue; they are admitted in FIFO order.
If the queue is full, the incoming request is rejected.
"""
def __init__(self, capacity: int):
self.capacit…
Chaos Inject Random Failures in Python
Simulate random failures in a Python function to test error handling and resilience, using random thresholds and controllable success rates.
import random
def unreliable_function(success_rate: float = 0.7) -> str:
"""Simulate a function that sometimes fails."""
if random.random() > success_rate:
raise ConnectionError("Simulated network failure")
return "Operation completed successfully"
if __name__ == "__main__":
random.seed(42)…
Circuit breaker failure threshold count in Python
Track consecutive or time-windowed failures with a deque to open a circuit breaker and auto-recover to half-open after a cooldown.
from collections import deque
from time import time, sleep
class CircuitBreaker:
def __init__(self, failure_threshold: int = 5, recovery_time: float = 10.0):
self.failure_threshold = failure_threshold
self.recovery_time = recovery_time
self.failures: deque[float] = deque()
self.st…
Exactly Once Processing Dedupe Mock in Python
Implements a streaming deduplicator using a set and queue to guarantee each item is processed exactly once while preserving insertion order.
from collections import deque
class DedupeStream:
def __init__(self):
self.seen = set()
self.queue = deque()
def add(self, item):
if item not in self.seen:
self.seen.add(item)
self.queue.append(item)
print(f"Processed: {item} (exactly once)")
…
Observability & SRE
Structured logging, metrics, tracing, health checks, and SLO-friendly instrumentation.
Adding a Correlation ID to Log Context in Python
Injects a correlation ID into the logging context using a context manager and a custom log record factory so every log line includes the ID.
import logging
import uuid
from contextlib import contextmanager
logging.basicConfig(level=logging.INFO, format='%(levelname)s | %(correlation_id)s | %(message)s')
@contextmanager
def correlation_id_context(correlation_id):
"""Temporarily inject a correlation_id into the logging context."""
extra = {'correl…
Calculate Error Rate from Log Stream in Python
Parses a mock log stream to count errors and compute the error percentage using a rolling window of recent entries.
import re
from collections import deque
def error_rate_from_log_stream(message):
log_pattern = r'^\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\] (ERROR|INFO|DEBUG): (.*)$'
recent_entries = deque(maxlen=100)
error_count = 0
total_count = 0
for line in message.strip().split('\n'):
match = re.mat…
Check if a Timestamp Falls in a Daily Maintenance Window in Python
A small Python function that returns True when a datetime falls inside a daily maintenance window, and a demo printing yes/no for sample timestamps.
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
def in_maintenance_window(now: datetime, start_hour: int = 2, duration_hours: int = 4) -> bool:
"""Return True if 'now' falls inside the daily maintenance window."""
day_start = now.replace(hour=start_hour, minute=0, second=0, microsecond…
Export Metrics with OTLP Mock in Python
Simulates system metric collection and exports them as an OTLP-like JSON payload using only Python's standard library.
from dataclasses import dataclass, asdict
import json
import random
import time
@dataclass
class Metric:
name: str
value: float
timestamp: int
unit: str = "1"
def collect_system_metrics() -> list[Metric]:
"""Mock metric collection for OTLP export simulation."""
now = int(time.time())
re…
Generate Mock CPU and Memory Metrics in Python
Build a mock_host_metrics() generator that outputs realistic CPU and memory usage percentages for monitoring demos and tests.
import time
import random
def mock_host_metrics():
"""Generate mock CPU and memory metrics for a host."""
cpu_percent = round(random.uniform(10.0, 95.0), 1)
memory_percent = round(random.uniform(20.0, 90.0), 1)
memory_used_mb = round(random.uniform(512, 8192), 1)
return {
"timestamp": in…
Generate Prometheus Text Exposition Format in Python
Mock a Prometheus metrics endpoint by formatting metrics into the text exposition format with HELP, TYPE, and sample lines.
import time
from random import randint
# Mock a Prometheus metrics endpoint output
metrics = {
"http_requests_total": {
"help": "Total number of HTTP requests",
"type": "counter",
"samples": [
{"labels": {"method": "get", "code": "200"}, "value": randint(1000, 9999)},
…
Microservices patterns
Service boundaries, discovery, inter-service calls, and decomposition patterns.
BFF aggregation pattern: combine multiple service responses in Python
Mock three backend services and aggregate their responses into one unified payload — the BFF pattern every Python microservice gateway relies on.
from dataclasses import dataclass
from typing import Any
@dataclass
class Service:
name: str
data: dict[str, Any]
def get_user_service() -> Service:
return Service("user", {"id": 1, "name": "Alice"})
def get_orders_service() -> Service:
return Service("orders", {"total": 299.99, "count": 2})
de…
Backward Compatible Schema Evolution in Python
A mock schema validator that evolves JSON schemas while preserving backward compatibility by keeping old fields and validating required ones.
import json
from copy import deepcopy
class SchemaValidator:
def __init__(self, schema):
self.schema = schema
def evolve(self, new_schema):
"""Evolve mock schema while keeping backward compatibility."""
for field in self.schema:
if field not in new_schema:
…
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…
CQRS with Separate Read and Write Repositories in Python
Implement CQRS in Python with separate write and read repositories, using commands for mutations and frozen DTOs for queries.
from dataclasses import dataclass
from typing import Dict, List, Optional
# --- Write side: commands mutate state ---
@dataclass
class CreateUserCommand:
id: int
name: str
class UserWriteRepository:
def __init__(self) -> None:
self._store: Dict[int, Dict[str, object]] = {}
def create(self,…
Cache-Aside Pattern in Python: Per-Service Mock
A Python mock of the cache-aside pattern for a single microservice—lazy-load from a database into an in-memory cache and invalidate on updates.
class ServiceCache:
def __init__(self):
self.database = {"user:1": "Alice", "user:2": "Bob", "user:3": "Charlie"}
self.cache = {}
def get_user(self, user_id):
cache_key = f"user:{user_id}"
if cache_key in self.cache:
print(f"CACHE HIT: {cache_key}")
retu…
Consumer Driven Contract Pact Mock in Python
Define and verify consumer-driven contracts using Pact's Consumer and Provider classes, mocking the provider to assert expected interactions.
from pact import Consumer, Provider
pact = Consumer('OrderService').has_pact_with(Provider('InventoryService'))
@Pact.verify()
class TestInventoryContract:
def test_get_inventory(self):
expected = {"item": "widget", "quantity": 100}
(pact
.given('inventory exists for widget')
.u…
Big data & Spark
PySpark jobs, partitioning, batch processing, and large-dataset transform patterns.
Accumulators Global Counter Mock in Python
Shows an accumulator-style global counter with a mock patch to control its value in tests.
import unittest
from unittest.mock import patch
# Module-level global counter accumulator
counter = 0
def increment(by=1):
"""Increment the global counter in place (accumulator pattern)."""
global counter
counter += by
return counter
def reset():
"""Reset the counter to zero."""
global count…
Approximate Distinct Count in Python with HyperLogLog
Mock a large data stream and estimate the number of distinct items with a HyperLogLog-style probabilistic counter to save memory.
import random
import string
from collections import Counter
import math
class ApproxCountDistinct:
def __init__(self, num_buckets=16):
self.num_buckets = num_buckets
self.max_zeros = [0] * num_buckets
def _hash(self, item):
# Simple string hash to a 32-bit integer
h = …
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…
Cache persist MEMORY_ONLY mock in Python
Mock a MEMORY_ONLY persistence cache in Python with an LRU eviction policy and optional persistence flag.
import time
class LRUCache:
def __init__(self, capacity, persistence="MEMORY_ONLY"):
self.capacity = capacity
self.persistence = persistence
self.cache = {}
self.access_order = []
self.hits = 0
self.misses = 0
def get(self, key):
if key in self.cache:
…
Compaction Small Files Mock in Python
Simulates a small-files compaction job by creating small mock files and merging them into a single output file using Python's standard library.
from pathlib import Path
import tempfile
import os
def create_small_files(directory: Path, file_count: int = 5, lines_per_file: int = 3):
"""Create several small mock files with sample content."""
directory.mkdir(exist_ok=True)
for i in range(file_count):
file_path = directory / f"part-{i:04d}.tx…
Delta Lake ACID Transaction Log Mock in Python
Simulates Delta Lake's transactional log with JSON files for atomic commits, versioned operations, and crash recovery
import json
import time
from pathlib import Path
class DeltaLog:
def __init__(self, path):
self.log_dir = Path(path)
self.log_dir.mkdir(parents=True, exist_ok=True)
self.version = 0
def _write_txn(self, action, payload):
txn = {
"version": self.version,
…
ML engineering pipelines
Feature prep, batch inference, model-serving hooks, and production ML workflow glue.
Bayesian Optimization in Python: A Simplified Mock Implementation
A toy Bayesian optimization loop with a Gaussian process prior, expected improvement acquisition, and noisy sampling to find a function's minimum.
import random
import math
class BayesianOptimizer:
def __init__(self, noise=0.1):
self.noise = noise
self.observations = []
def objective(self, x):
return (math.sin(3*x) + 0.5*x) / (1 + x**2)
def gaussian_process_prior(self, x1, x2, length_scale=0.5):
return math.…
Build a Data Helper Class in Python for ML Pipelines
A beginner-friendly Python class that summarizes, filters, and exports ML dataset rows as JSON.
from typing import List, Dict, Any
import json
class DataHelper:
"""Beginner-friendly helpers for ML data pipelines."""
def __init__(self, data: List[Dict[str, Any]]):
self.data = data
self.keys = list(data[0].keys()) if data else []
def summary(self) -> Dict[str, Any]:
"…
Build a Mock Random Forest Classifier in Python
Create a simple random-forest-like classifier with random majority voting between trees, including fit, predict, and predict_proba methods.
import random
class MockRandomForest:
def __init__(self, n_trees=10, random_state=42):
self.n_trees = n_trees
self.random_state = random_state
self.classes_ = None
self._class_counts = None
random.seed(random_state)
def fit(self, X, y):
self.classes_ = sorted(…
Champion Challenger Deployment Mock in Python
Simulates an A/B champion-challenger ML deployment workflow — comparing two mock model accuracies and deciding which to promote to production.
import random
import time
class ModelMocker:
def __init__(self, name="Model", accuracy=0.85):
self.name = name
self.accuracy = accuracy
def predict(self, data):
"""Simulate prediction with some randomness."""
time.sleep(0.005) # simulate compute time
return 1 if rando…
Compare Model A vs Model B Metrics in Python
A script that simulates and compares metrics between two ML models, showing a formatted diff table for quick insight.
import random
def compare_a_b(samples=5):
"""Mock comparison of model A vs model B predictions."""
metrics = ["accuracy", "precision", "recall", "f1"]
print(f"{'Metric':<12}{'Model A':>10}{'Model B':>10}{'Diff':>10}")
print("-" * 42)
random.seed(42)
for metric in metrics:
a = round(r…
Create a Minimal Great Expectations Suite Mock in Python
Build a small Python class that mimics a Great Expectations suite, storing and serializing column expectations as JSON.
import json
class GreatExpectationsSuite:
"""A minimal mock of a Great Expectations suite."""
def __init__(self, suite_name, expectations=None):
self.suite_name = suite_name
self.expectations = expectations or []
def add_expectation(self, expectation_type, column=None, kwargs=None):
…
A/B testing & experimentation
User bucketing, experiment metrics, statistical comparison, and rollout guardrails.
Bayesian A/B Test Credible Interval in Python
Simulates A/B test data and computes posterior credible intervals and the probability that variant B outperforms A using Bayesian Beta-Binomial inference.
import numpy as np
from scipy import stats
# Simulated A/B test data
n_A = 1000
n_B = 1000
conversions_A = 120
conversions_B = 140
# Prior: Beta(1, 1) uniform
alpha_prior, beta_prior = 1, 1
# Posterior parameters
alpha_A = alpha_prior + conversions_A
beta_A = beta_prior + n_A - conversions_A
alpha_B = alpha_prior +…
Benjamini Hochberg FDR Correction in Python
Implement the Benjamini-HHochberg false discovery rate (FDR) procedure in Python to control the expected proportion of false positives among rejected hypotheses.
import numpy as np
def benjamini_hochberg(p_values, alpha=0.05):
p_values = np.array(p_values)
n = len(p_values)
sorted_idx = np.argsort(p_values)
sorted_p = p_values[sorted_idx]
thresholds = (np.arange(1, n + 1) / n) * alpha
significant = sorted_p <= thresholds
if not significan…
Bonferroni Correction in Python
Applies the Bonferroni correction to a list of p-values to control the family-wise error rate when performing multiple comparisons.
import numpy as np
def bonferroni_correction(p_values, alpha=0.05):
"""Apply Bonferroni correction to a list of p-values."""
n = len(p_values)
corrected_alpha = alpha / n
significant = [p < corrected_alpha for p in p_values]
return corrected_alpha, significant
if __name__ == "__main__":
# Moc…
Bootstrap Confidence Interval in Python
Estimates a confidence interval for a statistic (like the mean) using bootstrap resampling in pure Python.
import random
def bootstrap_ci(data, statistic, n_bootstraps=1000, ci_level=0.95, seed=42):
random.seed(seed)
n = len(data)
boot_stats = []
for _ in range(n_bootstraps):
sample = [random.choice(data) for _ in range(n)]
boot_stats.append(statistic(sample))
boot_stats.sort()
l…
Check Covariate Balance in Python
Compute standardized mean differences and KS tests to check covariate balance between treatment and control groups in Python.
import numpy as np
from scipy import stats
def balance_check(treatment, covariate):
"""Check covariate balance between treatment and control groups."""
treat_vals = covariate[treatment == 1]
control_vals = covariate[treatment == 0]
# Standardized mean difference
pooled_std = np.sqrt((np.var(t…
Check Sample Ratio Mismatch in Python
Estimates the probability that a simple random sample's proportion differs from the population proportion by more than 10% using simulation.
import random
def sample_ratio_mismatch(population_size: int, sample_size: int, p: float) -> float:
"""
Estimate the probability that a simple random sample's proportion
differs from the population proportion by more than 10%.
"""
total_counts = [0, 0]
for _ in range(10000):
sample = …
Database scaling & optimization
Indexing, connection pooling, read replicas, query tuning, and throughput-aware SQL.
Approximate Count with HyperLogLog in Python
A mock HyperLogLog implementation uses hash-based registers to estimate cardinality of large datasets with sublinear memory.
import hashlib
class HyperLogLog:
def __init__(self, precision=4):
if precision < 4 or precision > 16:
raise ValueError("precision must be between 4 and 16")
self.precision = precision
self.registers = [0] * (1 << precision)
def _hash(self, value):
return int(hashl…
B-Tree Insert and In-Order Traversal in Python
Simulates a B-tree (order 2) with insert and split logic, then prints keys in sorted order via in-order traversal.
class BTreeNode:
def __init__(self, leaf=False):
self.leaf = leaf
self.keys = []
self.children = []
def is_full(self, t):
return len(self.keys) == 2 * t - 1
class BTree:
def __init__(self, t=2):
self.t = t
self.root = BTreeNode(leaf=True)
def insert(s…
Broadcast a Small Reference Table in Python
Simulates SQL-style broadcasting of a small lookup table against a larger fact table in memory for mockups or load tests.
import random
def broadcast_mock(target, source, columns):
result = {}
for col in columns:
if col in target and col in source:
result[col] = target[col] + [source[col][i % len(source[col])] for i in range(len(target[col]))]
elif col in target:
result[col] = target[col]
…
Build a Full Text Search Index in Python
Create a simple inverted index for full-text search with the standard library, supporting multi-word AND queries across documents.
import re
from collections import defaultdict
class SimpleTextIndex:
def __init__(self):
self.index = defaultdict(list)
self.documents = {}
def add_document(self, doc_id, text):
self.documents[doc_id] = text
words = set(re.findall(r'\w+', text.lower()))
for word in wo…
Build a Partial Index Mock in Python for Database Filtering
Simulate a partial database index by filtering keys with a predicate, then return a limited mock lookup dictionary.
data = [
"alpha", "beta", "gamma", "delta", "epsilon",
"zeta", "eta", "theta", "iota", "kappa"
]
filtered_keys = [item for item in data if len(item) >= 5]
def mock_partial_index(keys, filter_func, limit=3):
result = {}
for key in keys:
if not filter_func(key):
continue
res…
Composite index leftmost prefix in Python
Simulate a composite index in SQLite and check whether query columns match the leftmost prefix rule for index usage.
import sqlite3
def get_indexed_columns(table_name):
"""Simulate a composite index by reading column names that start with 'idx_'."""
conn = sqlite3.connect(":memory:")
conn.execute(f"CREATE TABLE {table_name} (id INTEGER, idx_col1 TEXT, idx_col2 INTEGER, other TEXT)")
conn.execute(f"CREATE INDEX idx_…
Auth & security at scale
OAuth2, JWT, IAM patterns, secrets rotation, and least-privilege service auth.
ACME LetsEncrypt Mock Challenge Server in Python
A minimal HTTP server that serves key authorizations for ACME/Let's Encrypt DNS-01 or HTTP-01 challenges during testing and validation.
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
# In-memory store simulating the ACME challenge token -> key authorization pair
challenge_store = {
"token_example": "token_example.key_authorization"
}
class AcmeChallengeHandler(BaseHTTPRequestHandler):
def do_GET(self):
# Extra…
AES GCM encryption and decryption in Python
Encrypt and decrypt data with AES-256-GCM using the cryptography library, including nonce generation and authenticated roundtrip verification.
import os
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
def aes_gcm_demo():
plaintext = b"confidential message"
key = AESGCM.generate_key(bit_length=256)
aesgcm = AESGCM(key)
nonce = os.urandom(12)
ciphertext = aesgcm.encrypt(nonce, plaintext, None)
decrypted = aesgcm.dec…
Build a Mock OIDC Userinfo Endpoint in Python with Flask
Create a local mock OIDC userinfo endpoint in Flask that returns a standard JSON user payload, ideal for testing auth flows without a real identity provider.
from flask import Flask, jsonify
app = Flask(__name__)
@app.route("/userinfo")
def userinfo():
mock_user = {
"sub": "1234567890",
"name": "John Doe",
"email": "john@example.com",
"email_verified": True,
"groups": ["admin", "dev"]
}
return jsonify(mock_user)
if __n…
ChaCha20-Poly1305 mock in Python
Simulates ChaCha20-Poly1305 AEAD encryption and authentication using SHA-256 as a deterministic keystream and tag generator.
from hashlib import sha256
import struct
def chacha20_block(key, counter, nonce):
"""Mock ChaCha20 block: deterministic pseudo-random keystream from key+counter+nonce."""
state_input = key + struct.pack("<I", counter) + nonce + b"ChaCha20"
return sha256(state_input).digest()[:64] # 64-byte keystream bloc…
ECDH key agreement in Python with cryptography
Simulate ECDH key exchange between Alice and Bob, derive a shared secret, and generate a symmetric key with HKDF using the cryptography library.
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
def ecdh_mock():
# Alice generates her key pair
alice_private = ec.generate_private_key(ec.SECP256R1())
alice_public = alice_pr…
Enforce TLS 1.2 Minimum in Python
Create an SSL context with a minimum TLS version of 1.2 to enforce secure connections.
import ssl
def get_min_tls_version():
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
context.minimum_version = ssl.TLSVersion.TLSv1_2
return context.minimum_version
if __name__ == "__main__":
min_version = get_min_tls_version()
print(f"Minimum TLS version set to: {min_version.name} (value: {mi…
Production deployment patterns
Graceful shutdown, prod config, rollouts, readiness probes, and ship-with-confidence checks.
Auto Rollback on Error Rate Exceeded in Python
Simulate a service that monitors a rolling window of request errors and automatically rolls back when the error rate exceeds a threshold.
import random
import time
def simulate_requests(total_requests=1000, rollback_threshold=0.2):
"""
Simulate a service that automatically rolls back when the error rate
exceeds a threshold within a rolling window.
"""
window_size = 100
errors_seen = []
rolled_back = False
for req_num i…
Automate Semantic Versioning with Conventional Commits in Python
Automatically bump a semantic version based on conventional commit messages (feat, fix, BREAKING CHANGE) and write the new version to a file.
import re
from pathlib import Path
def get_next_version(current: str, commit_messages: list[str]) -> str:
"""Return the next semantic version based on conventional commit messages."""
major, minor, patch = map(int, current.split("."))
if any(msg.startswith("BREAKING CHANGE") for msg in commit_messages):
…
Design a Data Helper for Beginners in Python
Build a beginner-friendly DataHelper class that loads, saves, appends, and summarizes JSON data with atomic file writes.
import json
from datetime import datetime
from pathlib import Path
class DataHelper:
"""A beginner-friendly helper for common data operations."""
def __init__(self, data=None, filepath=None):
self.data = data if data is not None else []
self.filepath = Path(filepath) if filepath else None
…
Docker healthcheck CMD mock in Python
Runs a subprocess to curl a health endpoint and returns exit code 0 when healthy, 1 when unhealthy, mimicking a Docker HEALTHCHECK command.
import subprocess
import sys
def run_healthcheck() -> int:
result = subprocess.run(["curl", "-fsS", "http://localhost:8080/health"], capture_output=True, text=True)
if result.returncode == 0:
print("healthy")
return 0
print("unhealthy", file=sys.stderr)
return 1
if __name__ == "__ma…
Generate a Mock Artifact Version Tag in Python
Creates a mock build artifact version tag from a branch name and build number, with a date stamp.
import re
from datetime import datetime
def mock_version_tag(branch_name: str, build_number: int) -> str:
"""Generate a mock build artifact version tag from branch and build number."""
branch_slug = re.sub(r'[^a-zA-Z0-9]+', '-', branch_name).strip('-').lower()
date_part = datetime.utcnow().strftime('%Y%m%…
Generate a docker-compose.yml with mock services in Python
Build a docker-compose.yml string from a Python dict of service names and images, then write it to a file.
import yaml
from pathlib import Path
def generate_mock_compose(services: dict) -> str:
compose = {
"version": "3.9",
"services": {}
}
for name, image in services.items():
compose["services"][name] = {
"image": image,
"container_name": f"mock-{name}",
…
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.