Reference library

Python Code Samples

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

2107 samples 1466 easy 636 medium 5 hard

Strings & text

Format, split, join, parse, and clean text — everyday Python string patterns.

View all 94 →
Strings & text easy

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.

password security validation
Python
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…
51 0 Open
Strings & text easy

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.

csv quotes strings
Python
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))
14 0 Open
Strings & text easy

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.

password security regex
Python
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'[!@#$%^&*(),.?":…
52 0 Open
Strings & text medium

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.

datetime natural-language regex
Python
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"…
59 0 Open
Strings & text easy

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.

text-analysis counter strings
Python
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)

…
15 0 Open
Strings & text easy

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.

string split join
Python
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)
14 0 Open

Lists & loops

Iterate, transform, and combine sequences with readable loop patterns.

View all 84 →
Lists & loops easy

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.

lists sorted all
Python
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…
18 0 Open
Lists & loops easy

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.

lists comparison loops
Python
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…
13 0 Open
Lists & loops easy

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.

join list comma
Python
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)
14 0 Open
Lists & loops easy

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.

enumerate iteration loops
Python
fruits = ["apple", "banana", "cherry", "date"]

for index, fruit in enumerate(fruits, start=5):
    print(f"{index}: {fruit}")
14 0 Open
Lists & loops easy

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.

lists filtering type-checking
Python
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…
13 0 Open
Lists & loops easy

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.

list enumerate loops
Python
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 …
13 0 Open

Functions & basics

Reusable building blocks — parameters, returns, scope, and clear function design.

View all 74 →
Functions & basics easy

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.

type-hints typing annotations
Python
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…
14 0 Open
Functions & basics easy

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.

timeit benchmark performance
Python
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…
12 0 Open
Functions & basics easy

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.

context manager contextlib file handling
Python
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…
13 0 Open
Functions & basics easy

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.

callback loops progress
Python
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…
13 0 Open
Functions & basics easy

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.

lru_cache caching decorators
Python
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…
13 0 Open
Functions & basics easy

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.

datetime timezone timedelta
Python
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…
43 0 Open

Errors & debugging

Handle failures gracefully, raise helpful errors, and debug with confidence.

View all 64 →
Errors & debugging easy

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.

recursion exceptions error-handling
Python
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…
12 0 Open
Errors & debugging easy

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.

error handling try except valueerror
Python
try:
    number = int("not_a_number")
except ValueError:
    print("That's not a valid number. Please enter digits only.")
12 0 Open
Errors & debugging medium

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.

validation exceptions errors
Python
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):
        …
12 0 Open
Errors & debugging easy

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.

try-except valueerror zerodivisionerror
Python
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…
11 0 Open
Errors & debugging medium

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.

logging correlation-id filter
Python
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…
12 0 Open
Errors & debugging easy

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.

assert debugging preconditions
Python
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}")
13 0 Open

Files & data

Read and write files safely; parse JSON, CSV, and common text formats.

View all 136 →
Files & data easy

Append a Line to a Log File in Python

Append a line to a file using a context manager and Path.open().

file-io logging pathlib
Python
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
  …
17 0 Open
Files & data easy

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.

file permissions os.walk audit
Python
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…
55 0 Open
Files & data easy

Automatically Detect Corrupted Files Using SHA-256 Checksums in Python

Compute SHA-256 checksums of files and compare them to detect corruption in Python.

checksum file-integrity hashlib
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…
55 1 Open
Files & data easy

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.

excel validation openpyxl
Python
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…
58 0 Open
Files & data easy

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.

cli json persistence
Python
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…
110 0 Open
Files & data easy

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.

os.walk file-index defaultdict
Python
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…
17 0 Open

Dictionaries & sets

Key–value maps, uniqueness, counting, grouping, and fast lookups.

View all 84 →
Dictionaries & sets medium

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.

dictionary case-insensitive wrapper
Python
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…
12 0 Open
Dictionaries & sets easy

Build a defaultdict histogram of categories in Python

Count occurrences of each category in a list using collections.defaultdict(int) for automatic initialization.

defaultdict histogram collections
Python
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", …
9 0 Open
Dictionaries & sets easy

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.

graph adjacency dictionary
Python
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)…
11 0 Open
Dictionaries & sets easy

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.

ordereddict dictionaries insertion-order
Python
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 …
12 0 Open
Dictionaries & sets easy

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.

dictionary mapping duplicate-check
Python
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…
15 0 Open
Dictionaries & sets easy

Compare Two Dictionaries in Python

Compare two dictionaries by finding common keys, unique keys, and value differences using Python's set operations.

dictionary set operations comparison
Python
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…
16 0 Open

OOP & classes

Classes, instances, methods, dataclasses, and object-oriented design in Python.

View all 69 →
OOP & classes easy

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.

property validation oop
Python
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…
15 0 Open
OOP & classes easy

Binary Tree Inorder Traversal in Python

Define a TreeNode class and recursively print in-order traversal (left, node, right) of a binary tree.

binary-tree recursion traversal
Python
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…
13 0 Open
OOP & classes medium

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__.

borg monostate shared-state
Python
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…
13 0 Open
OOP & classes medium

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.

bridge design-pattern oop
Python
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:
           …
14 0 Open
OOP & classes medium

Composable Predicates with the &, |, ~ Operators in Python

Define a reusable Predicate class that combines boolean checks with & (AND), | (OR), and ~ (NOT) operators.

predicates operator-overloading oop
Python
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…
12 0 Open
OOP & classes easy

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.

composition design-patterns oop
Python
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, …
12 0 Open

Algorithms & data structures

Classic patterns — search, sort, stacks, queues, and practical complexity-aware code.

View all 110 →
Algorithms & data structures medium

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.

binary search greedy capacity
Python
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 …
12 0 Open
Algorithms & data structures medium

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.

binary-search algorithms search
Python
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…
14 0 Open
Algorithms & data structures easy

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.

histogram bins statistics
Python
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…
16 0 Open
Algorithms & data structures medium

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.

two-pointer array algorithm
Python
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)
        …
13 0 Open
Algorithms & data structures easy

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.

brute-force nested-loops counting
Python
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]:
               …
13 0 Open
Algorithms & data structures easy

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.

dfs graph traversal
Python
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…
14 0 Open

Comprehensions & generators

List/dict/set comprehensions, generator expressions, and lazy iteration.

View all 69 →
Comprehensions & generators easy

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.

generators chunking database
Python
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"},
      …
13 0 Open
Comprehensions & generators medium

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.

generators pipeline lazy-evaluation
Python
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__":
   …
11 0 Open
Comprehensions & generators easy

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.

generator file-io lazy
Python
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…
13 0 Open
Comprehensions & generators easy

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.

generators iterators itertools
Python
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)
13 0 Open
Comprehensions & generators easy

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.

comprehensions generators list-comprehension
Python
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…
13 0 Open
Comprehensions & generators easy

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.

comprehensions generators counter
Python
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…
13 0 Open

AI & LLM integration patterns

Call LLM APIs, structure prompts, parse responses, and ship AI features safely.

View all 59 →
AI & LLM integration patterns easy

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.

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

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.

ai llm reasoning
Python
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…
15 0 Open
AI & LLM integration patterns medium

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.

circuit-breaker llm resilience
Python
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, …
13 0 Open
AI & LLM integration patterns easy

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.

cosine-similarity retrieval embeddings
Python
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…
14 0 Open
AI & LLM integration patterns easy

Demonstrate Prompt Injection Bypass in Python

Simulate why naive system prompt filters fail against prompt injection with casing and spacing variations.

prompt-injection llm-security demo
Python
# 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…
13 0 Open
AI & LLM integration patterns easy

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.

streaming tokens strings
Python
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…
15 0 Open

Automation & scripting

CLI tools, scheduled jobs, filesystem tasks, and glue scripts that save time.

View all 176 →
Automation & scripting easy

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.

logs regex counter
Python
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…
19 0 Open
Automation & scripting easy

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.

automation tweeting blog
Python
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",
    …
15 0 Open
Automation & scripting medium

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.

temporary-files cleanup automation
Python
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"),
  …
54 0 Open
Automation & scripting medium

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.

github api download
Python
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…
61 0 Open
Automation & scripting medium

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.

csv matplotlib charting
Python
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…
63 0 Open
Automation & scripting easy

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.

hardware inventory psutil
Python
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…
53 0 Open

Data pipelines & processing

ETL-style flows, batch transforms, validation, and moving data between formats.

View all 71 →
Data pipelines & processing easy

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.

csv uuid surrogate-key
Python
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…
13 0 Open
Data pipelines & processing easy

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.

lineage metadata dict-unpacking
Python
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"
    …
13 0 Open
Data pipelines & processing medium

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.

pandas excel data cleaning
Python
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…
45 0 Open
Data pipelines & processing medium

Check Null Rate Threshold in PySpark DataFrame

This PySpark code checks the null rate of specified DataFrame columns against a threshold and returns violations.

pyspark data quality null check
Python
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…
12 0 Open
Data pipelines & processing easy

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.

counter metrics data-pipeline
Python
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…
14 0 Open
Data pipelines & processing easy

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.

json pipeline helpers
Python
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,…
13 0 Open

Git + Python

Automate Git from Python — diffs, hooks, release tags, and repo housekeeping.

View all 53 →
Git + Python easy

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.

git subprocess automation
Python
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.…
13 0 Open
Git + Python easy

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.

bisect binary-search git
Python
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…
16 0 Open
Git + Python easy

Build a Simple Log Graph in Python

Create a basic one-dimensional bar chart from log lines by counting occurrences of leading numeric keys.

logging visualization graph
Python
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…
15 0 Open
Git + Python easy

Bump Semantic Version Git Tag in Python

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

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

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


def get_latest_tag() -> str:
    result = run(["git", "describe…
12 0 Open
Git + Python easy

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.

git parsing collections
Python
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):
    "…
12 0 Open
Git + Python easy

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

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

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

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

Cloud + Python

Cloud SDK patterns — storage, serverless handlers, secrets, and deployment helpers.

View all 59 →
Cloud + Python medium

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.

url shortener api
Python
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"{…
53 0 Open
Cloud + Python easy

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.

cloud-storage json file-io
Python
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…
14 0 Open
Cloud + Python easy

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.

json csv file-io
Python
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 =…
12 0 Open
Cloud + Python medium

Cross Account Role Chaining Mock Credentials in Python

Simulate AWS STS AssumeRole with mock credentials for cross-account role chaining in Python.

aws sts mock
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.""…
15 0 Open
Cloud + Python medium

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.

retry backoff jitter
Python
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…
17 0 Open
Cloud + Python easy

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.

cloudformation mock aws
Python
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"),
        ("…
14 0 Open

Modern tooling

uv, ruff, pyproject.toml, packaging, and current Python project workflows.

View all 60 →
Modern tooling easy

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.

subprocess command-runner recipes
Python
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…
12 0 Open
Modern tooling easy

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.

textual tui terminal
Python
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…
13 0 Open
Modern tooling easy

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.

ruff pyproject.toml tomllib
Python
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 = {
 …
11 0 Open
Modern tooling easy

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.

json datetime pathlib
Python
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…
11 0 Open
Modern tooling medium

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.

structlog logging mocking
Python
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…
16 0 Open
Modern tooling easy

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.

dataclass chaining filter
Python
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 …
13 0 Open

Concurrency & performance

asyncio, threading, multiprocessing, and profiling-friendly performance patterns.

View all 66 →
Concurrency & performance medium

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 performance list
Python
"""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…
11 0 Open
Concurrency & performance medium

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.

profiling cprofile pstats
Python
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()
  …
42 0 Open
Concurrency & performance medium

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.

threading context-manager graceful-shutdown
Python
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")
 …
14 0 Open
Concurrency & performance medium

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.

asyncio queue concurrency
Python
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…
13 0 Open
Concurrency & performance medium

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.

asyncio cancellation cleanup
Python
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…
12 0 Open
Concurrency & performance easy

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.

concurrency threadpoolexecutor parallelism
Python
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_…
14 0 Open

Testing & modern typing

pytest basics, mocks, type hints, TypedDict, Protocol, and static-checking patterns.

View all 70 →
Testing & modern typing easy

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.

pytest testing capture
Python
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…
11 0 Open
Testing & modern typing medium

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.

characterization-testing legacy-code testing
Python
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:
     …
13 0 Open
Testing & modern typing easy

Dataclass with Type Hints Fields in Python

Create a data class with typed fields and default values, then instantiate and inspect it.

dataclass type hints oop
Python
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…
11 0 Open
Testing & modern typing easy

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.

dependency-injection testing mocking
Python
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(…
14 0 Open
Testing & modern typing easy

Design Data Helpers with Python TypedDict and Literal

Use TypedDict, Literal, and Union to define typed data shapes and parse values in Python.

typeddict literal union
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…
11 0 Open
Testing & modern typing easy

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.

regression-testing unit-testing math
Python
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)
   …
15 0 Open

System design patterns

Sharding, load balancing, CAP tradeoffs, and scaling patterns — interview and production ready.

View all 56 →
System design patterns medium

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.

bff http-server aggregation
Python
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 [
            {…
16 0 Open
System design patterns easy

Builder pattern for mocking complex objects in Python

Use a fluent Builder to construct realistic mock objects with defaults, enabling readable test data setup.

builder-pattern mock-data testing
Python
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:
   …
14 0 Open
System design patterns medium

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.

circuit-breaker resilience fault-tolerance
Python
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):
     …
13 0 Open
System design patterns easy

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.

data-helper json csv
Python
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:
          …
14 0 Open
System design patterns medium

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.

ddd aggregate-root object-oriented
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:
       …
11 0 Open
System design patterns medium

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.

facade-pattern design-patterns abstraction
Python
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()
   …
14 0 Open

API design & gRPC

REST best practices, protobuf, API versioning, and backward-compatible service contracts.

View all 59 →
API design & gRPC medium

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.

http-server mock-api rest
Python
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…
14 0 Open
API design & gRPC medium

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.

rest-api http-server mock
Python
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.…
14 0 Open
API design & gRPC easy

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.

protobuf json grpc
Python
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…
15 0 Open
API design & gRPC easy

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.

dataclasses grpc api-design
Python
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…
13 0 Open
API design & gRPC easy

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.

dataclasses grpc serialization
Python
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…
13 0 Open
API design & gRPC easy

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.

openapi api-docs api-design
Python
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()
            …
14 0 Open

Streaming & messaging

Kafka-style pub/sub, event consumers, async pipelines, and message-driven workflows.

View all 53 →
Streaming & messaging easy

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.

fire-and-forget mock testing
Python
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
…
14 0 Open
Streaming & messaging medium

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.

streaming batch-processing queues
Python
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…
12 0 Open
Streaming & messaging easy

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.

streaming deque dataclass
Python
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…
12 0 Open
Streaming & messaging easy

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.

dead-letter-queue messaging retry
Python
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…
14 0 Open
Streaming & messaging easy

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.

deduplication streaming json
Python
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…
11 0 Open
Streaming & messaging easy

Event Envelope with Schema Version Field in Python

Build a typed event envelope dataclass with an explicit schema version field for mock streaming scenarios.

event dataclass messaging
Python
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…
14 0 Open

Caching & Redis

Cache-aside, TTL, invalidation, hot keys, and in-memory lookup patterns at scale.

View all 58 →
Caching & Redis easy

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.

caching cache-aside read-through
Python
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…
14 0 Open
Caching & Redis easy

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.

redis cache ttl
Python
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 …
13 0 Open
Caching & Redis medium

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.

caching null-object ttl
Python
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…
14 0 Open
Caching & Redis medium

Cache Stampede Prevention with SingleFlight in Python

Implements a SingleFlight pattern in Python to deduplicate concurrent cache-miss computations and prevent cache stampede.

caching concurrency singleflight
Python
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]
           …
14 0 Open
Caching & Redis easy

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.

caching ordereddict lru
Python
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:
          …
16 0 Open
Caching & Redis hard

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.

concurrency threading coalescing
Python
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…
13 0 Open

Reliability & rate limiting

Retries, exponential backoff, circuit breakers, token buckets, and idempotent handlers.

View all 57 →
Reliability & rate limiting medium

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.

idempotency at-least-once threading
Python
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:
          …
14 0 Open
Reliability & rate limiting easy

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.

rate-limiting decorator time
Python
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…
12 0 Open
Reliability & rate limiting easy

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.

admission-control queue rate-limiting
Python
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…
14 0 Open
Reliability & rate limiting easy

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.

chaos-engineering random resilience
Python
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)…
14 0 Open
Reliability & rate limiting medium

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.

circuit-breaker resilience deque
Python
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…
15 0 Open
Reliability & rate limiting easy

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.

deduplication exactly-once streaming
Python
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)")
      …
14 0 Open

Observability & SRE

Structured logging, metrics, tracing, health checks, and SLO-friendly instrumentation.

View all 56 →
Observability & SRE medium

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.

logging correlation-id context-manager
Python
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…
14 0 Open
Observability & SRE easy

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.

logging regex error-rate
Python
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…
14 0 Open
Observability & SRE easy

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.

maintenance datetime scheduling
Python
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…
14 0 Open
Observability & SRE medium

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.

otlp metrics observability
Python
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…
11 0 Open
Observability & SRE easy

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.

mock metrics monitoring
Python
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…
14 0 Open
Observability & SRE easy

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.

prometheus metrics observability
Python
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)},
         …
12 0 Open

Microservices patterns

Service boundaries, discovery, inter-service calls, and decomposition patterns.

View all 53 →
Microservices patterns easy

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.

bff aggregation microservices
Python
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…
11 0 Open
Microservices patterns medium

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.

schema-evolution json microservices
Python
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:
               …
14 0 Open
Microservices patterns medium

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.

bulkhead threadpool semaphore
Python
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…
10 0 Open
Microservices patterns medium

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.

cqrs repositories microservices
Python
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,…
13 0 Open
Microservices patterns easy

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.

caching microservices cache-aside
Python
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…
11 0 Open
Microservices patterns medium

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.

pact contract testing microservices
Python
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…
14 0 Open

Big data & Spark

PySpark jobs, partitioning, batch processing, and large-dataset transform patterns.

View all 49 →
Big data & Spark medium

Accumulators Global Counter Mock in Python

Shows an accumulator-style global counter with a mock patch to control its value in tests.

accumulator global state mock
Python
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…
13 0 Open
Big data & Spark medium

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.

hyperloglog distinct-count probabilistic
Python
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 = …
13 0 Open
Big data & Spark medium

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.

bloom filter join hashing
Python
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…
11 0 Open
Big data & Spark easy

Cache persist MEMORY_ONLY mock in Python

Mock a MEMORY_ONLY persistence cache in Python with an LRU eviction policy and optional persistence flag.

cache lru mock
Python
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:
 …
12 0 Open
Big data & Spark easy

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.

compaction file-io mock
Python
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…
15 0 Open
Big data & Spark medium

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

delta-lake transaction-log acid
Python
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,
           …
14 0 Open

ML engineering pipelines

Feature prep, batch inference, model-serving hooks, and production ML workflow glue.

View all 53 →
ML engineering pipelines medium

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.

bayesian-optimization gaussian-process hyperparameter-tuning
Python
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.…
10 0 Open
ML engineering pipelines easy

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.

data-helper ml-pipeline json
Python
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]:
        "…
14 0 Open
ML engineering pipelines easy

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.

random forest mock machine learning
Python
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(…
12 0 Open
ML engineering pipelines easy

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.

ml deployment champion-challenger
Python
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…
12 0 Open
ML engineering pipelines easy

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.

model comparison mock metrics
Python
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…
12 0 Open
ML engineering pipelines easy

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.

great-expectations mock testing
Python
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):
   …
10 0 Open

A/B testing & experimentation

User bucketing, experiment metrics, statistical comparison, and rollout guardrails.

View all 49 →
A/B testing & experimentation medium

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.

bayesian ab-testing credible-interval
Python
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 +…
13 0 Open
A/B testing & experimentation medium

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.

fdr multiple testing hypothesis testing
Python
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…
13 0 Open
A/B testing & experimentation easy

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.

statistics p-values multiple-comparisons
Python
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…
14 0 Open
A/B testing & experimentation medium

Bootstrap Confidence Interval in Python

Estimates a confidence interval for a statistic (like the mean) using bootstrap resampling in pure Python.

bootstrap confidence-interval statistics
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…
13 0 Open
A/B testing & experimentation medium

Check Covariate Balance in Python

Compute standardized mean differences and KS tests to check covariate balance between treatment and control groups in Python.

covariate balance ab-testing
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…
12 0 Open
A/B testing & experimentation medium

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.

simulation statistics ab-testing
Python
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 = …
14 0 Open

Database scaling & optimization

Indexing, connection pooling, read replicas, query tuning, and throughput-aware SQL.

View all 58 →
Database scaling & optimization medium

Approximate Count with HyperLogLog in Python

A mock HyperLogLog implementation uses hash-based registers to estimate cardinality of large datasets with sublinear memory.

hyperloglog cardinality hash
Python
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…
13 0 Open
Database scaling & optimization hard

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.

b-tree tree data-structure
Python
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…
12 0 Open
Database scaling & optimization easy

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.

broadcast mock-data data-engineering
Python
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]
…
13 0 Open
Database scaling & optimization medium

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.

search inverted-index text-processing
Python
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…
11 0 Open
Database scaling & optimization easy

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.

partial-index database mock
Python
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…
11 0 Open
Database scaling & optimization medium

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.

sqlite indexes database
Python
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_…
12 0 Open

Auth & security at scale

OAuth2, JWT, IAM patterns, secrets rotation, and least-privilege service auth.

View all 52 →
Auth & security at scale medium

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.

acme letsencrypt http-server
Python
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…
14 0 Open
Auth & security at scale medium

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.

aes-gcm cryptography encryption
Python
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…
17 0 Open
Auth & security at scale easy

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.

flask oidc userinfo
Python
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…
12 0 Open
Auth & security at scale medium

ChaCha20-Poly1305 mock in Python

Simulates ChaCha20-Poly1305 AEAD encryption and authentication using SHA-256 as a deterministic keystream and tag generator.

crypto aead mock
Python
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…
13 0 Open
Auth & security at scale medium

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.

ecdh cryptography key-agreement
Python
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…
14 0 Open
Auth & security at scale easy

Enforce TLS 1.2 Minimum in Python

Create an SSL context with a minimum TLS version of 1.2 to enforce secure connections.

tls ssl security
Python
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…
12 0 Open

Production deployment patterns

Graceful shutdown, prod config, rollouts, readiness probes, and ship-with-confidence checks.

View all 56 →
Production deployment patterns medium

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.

error-rate rollback rolling-window
Python
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…
14 0 Open
Production deployment patterns medium

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.

semantic-versioning conventional-commits automation
Python
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):
…
13 0 Open
Production deployment patterns easy

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.

json class pathlib
Python
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

 …
12 0 Open
Production deployment patterns easy

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.

docker healthcheck subprocess
Python
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…
13 0 Open
Production deployment patterns easy

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.

artifact versioning ci
Python
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%…
12 0 Open
Production deployment patterns easy

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.

docker compose yaml
Python
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}",
  …
16 0 Open

Guide: free Python code samples library

Copy-ready Python snippets for learners and developers

PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.

How to use this library

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. Run it in the IDE, tweak values, then take a related quiz or tutorial lesson

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.