Reference library

Python Code Samples

Easy snippets you can copy, study, and run in the browser editor.

21 matches
Files & data easy

Sync only changed files between two folders in Python

This code compares two folders and copies only the new or modified files from source to destination, skipping unchanged ones by comparing SHA-256 hashes.

files sync hashing
Python
import hashlib
from pathlib import Path
import shutil

def file_hash(path: Path, chunk_size: int = 8192) -> str:
    hasher = hashlib.sha256()
    with path.open("rb") as f:
        for chunk in iter(lambda: f.read(chunk_size), b""):
            hasher.update(chunk)
    return hasher.hexdigest()

def sync_files(src: s…
16 0 Open
Automation & scripting easy

Benchmark Disk Write Speed in Python with tempfile

Benchmark raw disk write performance by writing a temporary file in 1MB chunks and measuring throughput in MB/s.

benchmark tempfile performance
Python
import os
import tempfile
import time

def benchmark_write(size_mb=50):
    size_bytes = size_mb * 1024 * 1024
    chunk = b'x' * 1024 * 1024  # 1 MB chunk

    with tempfile.NamedTemporaryFile(delete=True) as tmp:
        start = time.perf_counter()
        written = 0
        while written < size_bytes:
            …
11 0 Open
Git + Python easy

How to sync a fork with upstream in Python

Run git fetch and merge commands from Python with subprocess to sync a forked repository with upstream/main.

git subprocess automation
Python
import subprocess
import sys


def sync_fork_with_upstream():
    """Simulate syncing a forked repo with upstream via git commands."""

    # Mock git operations: pretend to fetch from upstream and merge into main
    fetch_result = subprocess.run(
        ["git", "fetch", "upstream"],
        capture_output=True, tex…
12 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
Concurrency & performance easy

How to Memoize Async Functions with lru_cache in Python

Cache async function results with functools.lru_cache to avoid repeated expensive awaits, cutting total execution from ~0.4s to ~0.2s in this example.

asyncio lru_cache memoization
Python
from functools import lru_cache
import asyncio

@lru_cache(maxsize=128)
async def fetch_data(user_id: int) -> str:
    # Simulate expensive async operation
    await asyncio.sleep(0.1)
    return f"Data for user {user_id}"

async def main():
    start = asyncio.get_event_loop().time()
    
    # First calls (miss cach…
12 0 Open
Concurrency & performance easy

How to Run an Async Main with asyncio.run in Python

Show the canonical entry point for an asyncio program: define an async main, then launch it with asyncio.run.

asyncio event loop entry point
Python
import asyncio


async def main():
    print("Hello from async main")
    await asyncio.sleep(0.1)
    print("Done")


if __name__ == "__main__":
    asyncio.run(main())
16 0 Open
Concurrency & performance easy

How to Signal asyncio Workers to Stop with an Event in Python

Use an asyncio.Event to coordinate graceful shutdown of multiple concurrent worker tasks in Python.

asyncio events concurrency
Python
import asyncio
import random

async def worker(name, stop_event):
    while not stop_event.is_set():
        await asyncio.sleep(random.uniform(0.1, 0.5))
        print(f"Worker {name} processing...")
    print(f"Worker {name} stopped.")

async def main():
    stop_event = asyncio.Event()
    workers = [asyncio.create…
11 0 Open
Concurrency & performance easy

How to Test HTTPX Async Client Pool Reuse with Mocks in Python

Mock an httpx.AsyncClient to verify connection pool reuse by asserting GET calls share a single client instance across concurrent async requests.

httpx async-await mock
Python
import asyncio
import httpx
from unittest.mock import AsyncMock, patch, Mock

async def fetch_with_pool(client, url, n_reuses=3):
    results = []
    for i in range(n_reuses):
        resp = await client.get(url)
        results.append(resp.status_code)
        await asyncio.sleep(0)  # yield to loop to mimic real us…
13 0 Open
Concurrency & performance easy

How to Use ThreadPoolExecutor in Python for Parallel Processing

Use ThreadPoolExecutor with executor.map to run a function over many inputs concurrently and collect ordered results.

concurrency threadpoolexecutor parallel
Python
def worker(item):
    return item * item

if __name__ == "__main__":
    from concurrent.futures import ThreadPoolExecutor
    numbers = list(range(1, 11))
    with ThreadPoolExecutor(max_workers=4) as executor:
        results = list(executor.map(worker, numbers))
    print("Input:  ", numbers)
    print("Results:", …
13 0 Open
Concurrency & performance easy

How to Use threading.Lock to Synchronize a Counter in Python

Safely increment a shared counter across multiple threads using threading.Lock as a mutex to prevent race conditions.

threading lock mutex
Python
import threading

counter = 0
lock = threading.Lock()

def increment():
    global counter
    for _ in range(100000):
        with lock:
            counter += 1

threads = [threading.Thread(target=increment) for _ in range(5)]
for t in threads:
    t.start()
for t in threads:
    t.join()

print(f"Final counter valu…
14 0 Open
Concurrency & performance easy

How to Use uvloop Faster Event Loop

Install uvloop at startup to replace asyncio's default event loop with a faster libuv-based one, with a graceful fallback when it's unavailable.

uvloop asyncio event-loop
Python
import asyncio
try:
    import uvloop
    uvloop.install()
    USING_UVLOOP = True
except ImportError:
    USING_UVLOOP = False


async def fetch_data(index):
    await asyncio.sleep(0.01)
    return f"data-{index}"


async def main():
    tasks = [fetch_data(i) for i in range(10)]
    results = await asyncio.gather(*…
14 0 Open
Concurrency & performance easy

How to Wait for the First Future to Complete in Python

Use concurrent.futures.wait with FIRST_COMPLETED to pause until any task finishes and inspect the remaining pending futures.

concurrent.futures wait threading
Python
import concurrent.futures
import time


def task(name, delay):
    time.sleep(delay)
    return f"{name} done"


if __name__ == "__main__":
    with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
        futures = [
            executor.submit(task, "task1", 2),
            executor.submit(task, "ta…
13 0 Open
Concurrency & performance easy

How to set a timeout with asyncio.wait_for in Python

Use asyncio.wait_for to bound an async function with a timeout, catching TimeoutError when it exceeds the limit.

asyncio timeout concurrency
Python
import asyncio

async def slow_task():
    await asyncio.sleep(3)
    return "finished"

async def main():
    try:
        result = await asyncio.wait_for(slow_task(), timeout=1)
        print(result)
    except asyncio.TimeoutError:
        print("Task timed out")

if __name__ == "__main__":
    asyncio.run(main())
13 0 Open
Concurrency & performance easy

Run Background Tasks with asyncio.create_task in Python

Create background tasks in an asyncio event loop with asyncio.create_task and run them concurrently using asyncio.gather.

asyncio async concurrency
Python
import asyncio
import time

async def background_worker(name, duration):
    """Simulates a long-running background task."""
    print(f"{name} started at t={time.monotonic():.1f}")
    await asyncio.sleep(duration)
    print(f"{name} finished at t={time.monotonic():.1f}")

async def main():
    print(f"Main starting …
13 0 Open
Concurrency & performance easy

Synchronize Threads with a Barrier in Python

Demonstrates using threading.Barrier to synchronize multiple threads at phase boundaries, ensuring all workers wait for each other before proceeding.

threading synchronization barrier
Python
import threading
import time
from random import randint

def worker(barrier, worker_id):
    for phase in range(3):
        time.sleep(randint(1, 3))
        print(f"Worker {worker_id} finished phase {phase} at {time.time():.2f}")
        barrier.wait()
    print(f"Worker {worker_id}: all phases complete")

if __name_…
14 0 Open
Concurrency & performance easy

Thread-Safe Producer Consumer Queue in Python

A producer-consumer pattern using thread-safe queue.Queue with two threads, demonstrating safe communication and synchronized task completion.

queue threading producer-consumer
Python
import queue
import threading
import time
import random


def producer(q, item_count):
    for i in range(item_count):
        item = random.randint(1, 100)
        q.put(item)
        print(f"Producer added: {item}")
        time.sleep(0.1)


def consumer(q):
    while True:
        try:
            item = q.get(time…
12 0 Open
Concurrency & performance easy

asyncio sleep cooperative scheduling demo in Python

This demo shows how asyncio.sleep yields control between concurrent tasks, letting multiple workers interleave their ticks.

asyncio concurrency scheduling
Python
import asyncio

async def worker(name, delay):
    for i in range(3):
        print(f"{name}: tick {i}")
        await asyncio.sleep(delay)
    return f"{name} done"

async def main():
    tasks = [
        asyncio.create_task(worker("A", 0.1)),
        asyncio.create_task(worker("B", 0.2)),
        asyncio.create_tas…
12 0 Open
API design & gRPC easy

How to Build a WebSocket Echo Server in Python with asyncio

Create a simple WebSocket echo server using the websockets library and asyncio to handle concurrent connections.

websockets asyncio server
Python
import asyncio
import websockets

async def echo(websocket):
    async for message in websocket:
        await websocket.send(f"Echo: {message}")

async def main():
    async with websockets.serve(echo, "localhost", 8765):
        print("WebSocket server started on ws://localhost:8765")
        await asyncio.Future() …
15 0 Open
API design & gRPC easy

How to Poll an Operation Status Endpoint in Python

Mock a polling endpoint in Python that simulates checking an async operation's status until it completes or times out.

polling api async
Python
import time
import random


def poll_status(url: str, timeout: float = 5.0) -> dict:
    """Mock a polling endpoint that eventually returns a completed status."""
    start = time.time()
    while time.time() - start < timeout:
        # Simulate delayed response
        time.sleep(0.2)
        # 80% chance to report …
13 0 Open
Microservices patterns easy

How to Compose Parallel API Calls in Python with asyncio.gather

Compose multiple mock API responses in parallel using asyncio.gather with per-service simulated latency.

asyncio concurrency api
Python
import asyncio
import random
import time

async def mock_api(name: str, delay: float) -> dict:
    await asyncio.sleep(delay)
    return {"service": name, "value": random.randint(1, 100)}

async def fetch_all():
    services = {
        "users": mock_api("users", 0.2),
        "orders": mock_api("orders", 0.3),
      …
15 0 Open
Database scaling & optimization easy

How to Optimize SQLite Database Performance in Python

A Python helper that creates an index, enables WAL mode, and tunes synchronous settings to optimize SQLite database performance.

sqlite database optimization
Python
import sqlite3

DATABASE_PATH = "beginners.db"
UNOPTIMIZED_TABLE_SCHEMA = """
CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    email TEXT NOT NULL
)
"""


def optimize_database(db_path: str = DATABASE_PATH) -> dict:
    with sqlite3.connect(db_path) as connection:
        curs…
14 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.