Reference library

Python Code Samples

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

24 matches
Errors & debugging medium

How to attach a request ID to exception messages in Python

This code shows how to enrich exception messages with contextual request IDs using context variables, making error logs more traceable across concurrent requests.

contextvars exception-handling logging
Python
import logging
from contextvars import ContextVar

request_id_var = ContextVar("request_id", default="unknown")

def add_request_id(exc: Exception) -> Exception:
    exc.args = (f"request_id={request_id_var.get()} | {exc.args[0]}" if exc.args else f"request_id={request_id_var.get()}",) + exc.args[1:]
    return exc

d…
12 0 Open
Files & data medium

How to Atomically Write Files in Python with Temp File and Rename

Write a file atomically using a temporary file and os.replace so readers never see partial writes even if the process crashes mid-write.

atomic-write tempfile fsync
Python
import os
import tempfile
from pathlib import Path

def atomic_write(path: str | Path, content: str) -> None:
    """Write content to path atomically using a temp file and rename."""
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)

    fd, temp_path = tempfile.mkstemp(
        dir=str(path.par…
17 0 Open
Files & data medium

How to Sync Two Folders in Python (Lightweight Backup)

A Python script that synchronizes a source folder to a destination folder, copying new or updated files and removing files that no longer exist in the source.

sync backup filesystem
Python
import os
import shutil
import sys
from pathlib import Path

def sync_folders(src: Path, dst: Path):
    """Sync src folder to dst folder, copying missing/updated files."""
    dst.mkdir(parents=True, exist_ok=True)

    for src_path in src.rglob("*"):
        relative = src_path.relative_to(src)
        dst_path = ds…
37 0 Open
Automation & scripting medium

How to Sync Two Directories in Python (rsync-like)

Mirror a source directory into a destination by copying new or changed files and deleting extras, similar to rsync.

sync directory rsync
Python
import os
import shutil
import sys
from pathlib import Path

def sync_dirs(src: Path, dst: Path):
    """Mirror src into dst: copy new files, overwrite changed, delete extras."""
    dst.mkdir(parents=True, exist_ok=True)
    for dst_entry in dst.rglob('*'):
        rel = dst_entry.relative_to(dst)
        src_entry =…
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…
14 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…
13 0 Open
Concurrency & performance medium

How to Implement a Batch Requests Flush Interval in Python

A simple async batcher that accumulates items and flushes them either when a max batch size is reached or after a time-based flush interval.

asyncio batching concurrency
Python
import asyncio
from collections import deque

class Batcher:
    def __init__(self, flush_interval=0.5, max_batch=5):
        self.flush_interval = flush_interval
        self.max_batch = max_batch
        self.queue = deque()
        self.lock = asyncio.Lock()

    async def add(self, item):
        async with self.l…
13 0 Open
Concurrency & performance medium

How to Implement a Token Bucket Rate Limiter with asyncio in Python

This code implements a thread-safe token bucket rate limiter for asyncio, allowing you to limit the rate of async tasks or API calls.

asyncio rate-limiting token-bucket
Python
import asyncio
import time


class TokenBucket:
    def __init__(self, rate_per_second, capacity):
        self.rate = rate_per_second
        self.capacity = capacity
        self.tokens = capacity
        self.last_refill = time.monotonic()
        self.lock = asyncio.Lock()

    async def acquire(self):
        asy…
14 0 Open
Concurrency & performance medium

How to Mock anyio.run Backends (asyncio vs trio) in Python

Demonstrates how to mock anyio.run to verify backend selection (asyncio or trio) without actually running the event loop.

anyio async testing
Python
import anyio
from unittest.mock import Mock, patch


async def fetch_data():
    await anyio.sleep(0.1)
    return {"data": 42}


def run_with_backend(backend: str):
    async def main():
        result = await fetch_data()
        print(f"[{backend}] Result: {result}")

    anyio.run(main, backend=backend)


if __nam…
13 0 Open
Concurrency & performance medium

How to Mock asyncio.open_connection in Python

Mock asyncio.open_connection with AsyncMock to test async code without a real network connection.

asyncio testing mocking
Python
import asyncio
from unittest.mock import AsyncMock, patch


async def fetch_data(reader: asyncio.StreamReader) -> str:
    data = await reader.readline()
    return data.decode().strip()


async def main() -> None:
    # Mock asyncio.open_connection to simulate a server response
    mock_reader = AsyncMock()
    mock_…
14 0 Open
Concurrency & performance medium

How to Run Blocking Code in an Executor with asyncio in Python

This code runs blocking functions concurrently without stalling the event loop by offloading them to thread pool executors via asyncio.

asyncio executor concurrency
Python
import asyncio
import time


def blocking_task(name: str, duration: float) -> str:
    """Simulate a blocking operation."""
    time.sleep(duration)
    return f"Finished {name} after {duration}s"


async def main() -> None:
    loop = asyncio.get_running_loop()
    results = await asyncio.gather(
        loop.run_in_…
13 0 Open
Concurrency & performance medium

How to Run Coroutines Concurrently with asyncio.gather in Python

Run multiple async coroutines concurrently and collect their results in the order they were passed.

asyncio concurrency gather
Python
import asyncio


async def fetch_data(name: str, delay: float) -> str:
    """Simulate an async operation (e.g., API call) with a delay."""
    await asyncio.sleep(delay)
    return f"{name} data (after {delay}s)"


async def main() -> None:
    """Run multiple coroutines concurrently with asyncio.gather."""
    resul…
14 0 Open
Concurrency & performance medium

How to Use a Bounded Buffer with threading.Condition in Python

Implement a thread-safe bounded buffer using threading.Condition and show a producer–consumer example with exact output.

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

class BoundedBuffer:
    def __init__(self, capacity):
        self.capacity = capacity
        self.buffer = []
        self.condition = threading.Condition()

    def put(self, item):
        with self.condition:
            while len(self.buffer) >= self.capacity:
       …
14 0 Open
Concurrency & performance medium

How to Use asyncio Lock to Protect a Shared Counter in Python

This code demonstrates how to use an asyncio.Lock to safely increment a shared counter from multiple concurrent coroutines.

asyncio lock concurrency
Python
import asyncio

async def increment(counter, lock, increments):
    for _ in range(increments):
        async with lock:
            counter[0] += 1

async def main():
    counter = [0]
    lock = asyncio.Lock()
    tasks = [
        increment(counter, lock, 1000)
        for _ in range(5)
    ]
    await asyncio.gath…
16 0 Open
Concurrency & performance medium

How to Use threading.RLock in Python

Demonstrates threading.RLock, a reentrant lock that allows the same thread to acquire it multiple times without deadlocking — essential for recursive functions sharing state across threads.

threading rlock concurrency
Python
import threading
import time

lock = threading.RLock()
shared_counter = 0

def recursive_increment(value, depth):
    global shared_counter
    with lock:
        shared_counter += 1
        print(f"Depth {depth}: counter = {shared_counter}")
        if depth > 1:
            recursive_increment(value, depth - 1)

def…
14 0 Open
Concurrency & performance medium

Limit Concurrency with asyncio.Semaphore in Python

Use asyncio.Semaphore to cap how many async tasks run at once, throttling a batch of coroutines to a set concurrency limit.

asyncio concurrency semaphore
Python
import asyncio
import random


async def fetch_data(i: int, semaphore: asyncio.Semaphore) -> str:
    async with semaphore:
        print(f"Task {i} starts")
        await asyncio.sleep(random.uniform(0.1, 0.5))
        print(f"Task {i} finishes")
        return f"Result {i}"


async def main() -> None:
    semaphore …
13 0 Open
Concurrency & performance medium

Mocking Trio's open_nursery and spawn with asyncio.TaskGroup

Show how to mock Trio's nursery pattern using Python's asyncio.TaskGroup to simulate task spawning and completion.

asyncio taskgroup concurrency
Python
import asyncio

class MockSpawner:
    async def spawn(self, nursery):
        print("Spawning mock task...")
        await asyncio.sleep(1)
        print("Mock task completed")

async def open_nursery():
    async with asyncio.TaskGroup() as nursery:
        mock = MockSpawner()
        nursery.create_task(mock.spawn…
14 0 Open
Concurrency & performance medium

asyncio Condition wait notify pattern in Python

Coordinate coroutines with asyncio.Condition: workers wait for notifications and the main task notifies one or all of them.

asyncio concurrency synchronization
Python
import asyncio


async def worker(condition, name):
    async with condition:
        print(f"{name} waiting...")
        await condition.wait()
        print(f"{name} notified!")


async def main():
    condition = asyncio.Condition()
    tasks = [asyncio.create_task(worker(condition, f"worker-{i}")) for i in range(3…
14 0 Open
System design patterns medium

Microkernel Plug-in Core Mock in Python

Implements a minimal microkernel plug-in core that registers, unregisters, and executes synchronous or asynchronous plugins via a pluggable manager class.

microkernel plugin design-patterns
Python
import json
import abc
import inspect


class MicrokernelCore(abc.ABC):

    def __init__(self):
        self._plugins = {}

    def register(self, name, plugin):
        self._plugins[name] = plugin

    def unregister(self, name):
        return self._plugins.pop(name, None)

    def execute(self, name, *args, **kwa…
13 0 Open
API design & gRPC medium

How to Mock a 202 Accepted Long-Running Operation in Python

Build a mock HTTP server that returns a 202 Accepted response immediately and simulates a long-running operation in the background with threading.

api mock-server http
Python
import time
import threading
from http.server import HTTPServer, BaseHTTPRequestHandler

class MockHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        if self.path == "/long-running":
            self.send_response(202)
            self.send_header("Content-Type", "application/json")
            self.end_h…
13 0 Open
Caching & Redis medium

How to implement a write-behind cache with async queue in Python

Build an async write-behind cache that queues writes in memory and flushes them in batches to persistent storage.

write-behind cache asyncio
Python
import asyncio
from collections import deque
from dataclasses import dataclass

@dataclass
class CacheEntry:
    key: str
    value: str

class WriteBehindCache:
    def __init__(self, flush_interval=1.0):
        self.cache = {}
        self.queue = deque()
        self.flush_interval = flush_interval
        self._f…
14 0 Open
Reliability & rate limiting medium

How to Propagate Context Variables with asyncio in Python

Use Python's ContextVar with asyncio to carry deadline information across concurrent tasks and propagate context automatically.

contextvars asyncio concurrency
Python
import asyncio
from contextvars import ContextVar
from datetime import datetime

deadline = ContextVar("deadline", default=None)

async def worker(name):
    current = deadline.get()
    if current:
        print(f"{name} sees deadline: {current}")
    else:
        print(f"{name} sees no deadline")
    await asyncio.…
13 0 Open
Microservices patterns medium

Distributed tracing with contextvars in Python

Propagate trace and span IDs across function calls using contextvars to mock distributed tracing in a single process.

tracing contextvars microservices
Python
import contextvars
import uuid
import time

_trace_context = contextvars.ContextVar("trace_context", default=None)


class TraceContext:
    def __init__(self, trace_id, parent_span_id):
        self.trace_id = trace_id
        self.parent_span_id = parent_span_id
        self.span_id = uuid.uuid4().hex[:16]
        s…
13 0 Open
Production deployment patterns medium

How to Build a GitOps Argo CD Sync Mock in Python

Simulate Argo CD-style GitOps deployment sync with Python dataclasses, random success rates, and force-sync retry logic.

gitops argo-cd deployment
Python
import random
import time
from dataclasses import dataclass, field
from typing import List, Dict


@dataclass
class Application:
    name: str
    source_repo: str
    target_revision: str
    synced: bool = False
    health_status: str = "Healthy"
    history: List[Dict] = field(default_factory=list)

    def sync(se…
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.