Reference library

Python Code Samples

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

82 matches
Files & data medium

Chunk Large File Upload Simulation by Blocks in Python

A Python script reads a large binary file in fixed-size chunks and simulates a block-by-block upload with per-chunk SHA256 hashing.

file i/o chunking hashing
Python
import os
import hashlib
from pathlib import Path


def read_file_in_chunks(file_path, chunk_size=8196):
    """Yield chunks of a file as bytes."""
    with open(file_path, 'rb') as f:
        while chunk := f.read(chunk_size):
            yield chunk


def simulate_chunked_upload(file_path, chunk_size=8196):
    """S…
15 0 Open
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 …
13 0 Open
Algorithms & data structures medium

Game of Life Next State Grid in Python

Compute the next generation of Conway's Game of Life from a 2D grid using the standard three rules with neighbor counting.

game-of-life grid cellular-automaton
Python
def next_state(grid):
    m, n = len(grid), len(grid[0])
    new = [[0] * n for _ in range(m)]
    for r in range(m):
        for c in range(n):
            total = 0
            for dr in (-1, 0, 1):
                for dc in (-1, 0, 1):
                    if dr == 0 and dc == 0:
                        continue
   …
14 0 Open
AI & LLM integration patterns easy

How to Stream Tokens from a Mock LLM in Python

Simulate real-time LLM streaming by yielding tokens one at a time with a delay, making it easy to test streaming UIs.

generator llm streaming
Python
import time
from typing import Generator


def stream_tokens(text: str, delay: float = 0.05) -> Generator[str, None, None]:
    """Simulate an LLM streaming tokens word by word."""
    for word in text.split():
        yield word
        time.sleep(delay)


if __name__ == "__main__":
    sample = "Hello world! This is…
15 0 Open
Automation & scripting medium

How to Implement a Weighted DNS Resolver with Failover in Python

Simulates a weighted DNS load balancer that distributes traffic across IPs by weight and automatically fails over when a server is marked unhealthy.

dns load-balancing failover
Python
import random
import time

class WeightedDNSResolver:
    def __init__(self, records):
        self.records = records  # list of (ip, weight)
        self.total_weight = sum(weight for _, weight in records)
        self.failed_ips = set()

    def resolve(self):
        available = [(ip, weight) for ip, weight in self…
13 0 Open
Automation & scripting easy

How to Simulate a Traceroute in Python

This Python script simulates a network traceroute by generating mock hop IPs, random delays, and a destination reach condition, useful for testing network scripts.

traceroute simulation network
Python
import random
import time

def simulate_traceroute(destination, max_hops=30):
    """Simulate a traceroute to a destination with mock hop delays."""
    print(f"Traceroute to {destination} ({max_hops} hops max):")
    for hop in range(1, max_hops + 1):
        # Mock IP address for the hop
        mock_ip = f"10.0.{ra…
15 0 Open
Automation & scripting easy

Mock Certbot Renewal in Python for Testing

Simulates a Let's Encrypt certificate renewal by writing a mock certificate file and printing realistic certbot CLI output, without calling the actual certbot.

certbot letsencrypt automation
Python
import subprocess
import sys
from datetime import datetime, timedelta
from pathlib import Path


def renew_cert(domain: str, output_dir: str = "certs") -> str:
    """Simulate a Let's Encrypt renewal with mock certbot output."""
    out = Path(output_dir)
    out.mkdir(parents=True, exist_ok=True)

    cert_path = out…
16 0 Open
Automation & scripting easy

Toggle VPN Mock Network Manager Script in Python

Simulate a VPN manager with connect, disconnect, toggle, and status methods for testing or demo workflows.

vpn simulation automation
Python
import time

class MockVPNManager:
    def __init__(self):
        self.is_connected = False
        self.servers = ["us-west", "eu-central", "asia-east"]
        self.active_server = None

    def toggle(self):
        if self.is_connected:
            self.disconnect()
        else:
            self.connect()

    d…
11 0 Open
Git + Python easy

How to Mock Git Clean Dry Run in Python

Simulate the output of `git clean -n` in Python to preview which untracked files would be removed without actually deleting them.

git clean dry-run
Python
import subprocess
import sys

def mock_git_clean_dry_run(untracked_files):
    """Simulate `git clean -n` for a given list of untracked files."""
    if not untracked_files:
        print("No untracked files to remove.")
        return

    print("Would remove:")
    for file in untracked_files:
        print(f"  {fil…
14 0 Open
Git + Python easy

How to Mock Git Worktree Creation in Python

Create a mock Git worktree setup with parallel branch directories and state files for testing or simulation.

git worktree mock
Python
import os
import tempfile
from pathlib import Path

def create_mock_worktree(base_dir: Path, branches: list[str]) -> dict[str, Path]:
    """
    Mock Git worktree creation: creates parallel directories for each branch
    under the base directory, simulating independent worktrees.
    """
    worktrees = {}
    for b…
14 0 Open
Git + Python easy

How to Mock git sparse-checkout Paths in Python

Simulates git sparse-checkout configuration by writing desired paths to the sparse-checkout file without running git commands.

git sparse-checkout mocking
Python
import subprocess
from pathlib import Path
import tempfile


def configure_sparse_checkout(repo_dir: Path, paths: list[str]) -> list[str]:
    """Simulate sparse checkout configuration by returning the paths that would be set."""
    sparse_checkout_file = repo_dir / ".git" / "info" / "sparse-checkout"
    sparse_chec…
10 0 Open
Git + Python easy

Merge branch no ff mock in Python

Simulate a Git non-fast-forward merge in Python, producing a synthetic merge commit log for branches with differing SHAs.

git merge simulation
Python
class MergeResult:
    def __init__(self, base, branch):
        self.base = base
        self.branch = branch
        self.commit_log = []
        self.merged = False

    def simulate_merge(self):
        """Simulate a 'no-ff' merge by creating a new commit that references both branches."""
        if self.base == s…
13 0 Open
Cloud + Python easy

How to Mock Auto Scaling Policy Scale Out in Python

Define a mock auto-scaling function that scales out capacity by a factor up to a max, simulating AWS-like events.

auto-scaling cloud simulation
Python
def mock_scale_out(current_capacity: int, max_capacity: int, scale_factor: int = 1) -> tuple:
    """
    Mock auto-scaling policy: scales out by the specified factor
    if capacity allows, capped at max_capacity.
    """
    if current_capacity >= max_capacity:
        return current_capacity, False
    
    new_cap…
14 0 Open
Cloud + Python easy

Mock AWS Spot Instance Interruption Handler in Python

A Python class that simulates AWS Spot instance interruption checks, handling the 10% chance of termination, logging state-saving, and storing notice details.

aws spot-instances simulation
Python
import time
import random

class SpotInstanceHandler:
    def __init__(self, instance_id):
        self.instance_id = instance_id
        self.interruption_notices = []

    def start(self):
        print(f"Spot instance {self.instance_id} started")

    def check_interruption(self):
        # Simulate random interrup…
13 0 Open
Cloud + Python easy

Pick a Random Region with Mock Carbon Intensity in Python

Selects a random region from a list and generates a mock carbon intensity value using Python's random module.

random mock-data cloud
Python
import random

def pick_region_intensity(regions, seed=42):
    random.seed(seed)
    selected = random.choice(regions)
    intensity = random.randint(1, 10)
    return selected, intensity

if __name__ == "__main__":
    regions = ["North", "South", "East", "West"]
    selected, intensity = pick_region_intensity(regio…
14 0 Open
Modern tooling easy

How to Mock a Fast uv pip sync in Python

Simulate a fast uv pip sync by mocking file operations and subprocess calls to test dependency installation workflows.

uv mocking pip
Python
import os
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path

def uv_pip_sync_fast_install_mock(requirements_text: str) -> dict:
    """Simulate a fast uv pip sync by mocking file operations and subprocess calls."""
    mock_dir = Path(tempfile.mkdtemp(prefix="uv_mock_"))
    req_lines…
14 0 Open
Modern tooling easy

How to Mock docker compose up Healthcheck in Python

Simulate docker compose up with a healthcheck cycle using Python loops, delays, and simulated service statuses.

docker healthcheck simulation
Python
import subprocess
import time

def run_healthcheck():
    """Mock a docker compose up with a healthcheck cycle."""
    services = ["web", "db", "cache"]
    
    print("Starting docker compose services...")
    for service in services:
        print(f"[{service}] starting...")
        time.sleep(0.1)
        print(f"[…
15 0 Open
System design patterns medium

Simulate a Leaky Bucket Rate Limiter in Python

This code implements a leaky bucket rate limiter that drains at a fixed rate and accepts or rejects incoming requests based on capacity.

rate limiting leaky bucket simulation
Python
import time
from collections import deque


class LeakyBucket:
    """Simulates a leaky bucket rate limiter with a fixed drain rate."""
    def __init__(self, capacity, drain_rate_per_sec):
        self.capacity = capacity
        self.drain_rate = drain_rate_per_sec
        self.water = 0.0
        self.last_refill =…
13 0 Open
Streaming & messaging easy

How to Mock Kafka Topic Partitions with a Python dict of lists

Mocks a Kafka topic and its partitions using a defaultdict of lists to simulate message production, consumption, and per-partition counts.

kafka mock partitions
Python
from collections import defaultdict

class KafkaTopicPartitionMock:
    """A simple mock for Kafka topic-partition assignment using dict of lists."""

    def __init__(self, topic):
        self.topic = topic
        self.partitions = defaultdict(list)  # partition_id -> list of messages

    def produce(self, message…
15 0 Open
Streaming & messaging medium

How to Simulate RabbitMQ Exchange Routing in Python

Simulate RabbitMQ exchange routing using a nested dict, matching routing keys against patterns like error.* and info.# to return bound queues.

rabbitmq routing messaging
Python
from collections import defaultdict

def route_message(exchanges, exchange_name, routing_key):
    """
    Simulate RabbitMQ exchange routing using a nested dict structure.
    Returns list of queue names that match the routing key.
    """
    queues = exchanges.get(exchange_name, {})
    matched = []
    
    for pa…
14 0 Open
Streaming & messaging medium

Implement a retry queue with visibility timeout in Python

This code simulates a message queue with a visibility timeout, allowing messages to be retried if not deleted before the timeout expires.

queue retry visibility-timeout
Python
import time
from collections import deque


class SimpleQueue:
    def __init__(self, visibility_timeout=2):
        self.queue = deque()
        self.in_flight = {}
        self.visibility_timeout = visibility_timeout

    def send(self, message):
        self.queue.append(message)

    def receive(self):
        if …
13 0 Open
Streaming & messaging medium

Mock Watermark Late Event Side Output in Python

Simulates watermarking in a streaming pipeline by classifying events as on-time or late using timestamps and delays.

watermark streaming side output
Python
from datetime import datetime, timedelta
from typing import List, Tuple


def watermark_mock(
    events: List[Tuple[datetime, str]], watermark_delay: timedelta, max_delay: timedelta
) -> Tuple[List[Tuple[datetime, str]], List[Tuple[datetime, str]]]:
    """Simulate watermarking: events arriving on time vs. late by ch…
11 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…
16 0 Open
Reliability & rate limiting easy

Fixed Window Counter Rate Limiting in Python

A simple fixed window counter rate limiter that allows a maximum number of requests per 60-second window, with a mock time simulation.

rate-limiting fixed-window time
Python
from collections import deque
from time import time

class FixedWindowCounter:
    def __init__(self, max_requests):
        self.max_requests = max_requests
        self.window_start = int(time())
        self.window_count = 0

    def allow_request(self):
        current_time = int(time())
        if current_time >=…
13 0 Open

Browse by section

Each section groups closely related Python snippets.

Guide: free Python code samples library

Copy-ready Python snippets for learners and developers

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

How to use this library

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

Samples vs tutorials and challenges

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