Python Code
Samples
Medium snippets you can copy, study, and run in the browser editor.
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.
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…
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.
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…
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.
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…
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.
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 =…
How to Build a Producer-Consumer Pattern with asyncio.Queue in Python
This code implements a classic producer-consumer pattern using asyncio.Queue to coordinate one producer task that generates items and two consumer tasks that process them concurrently, with a sentinel value to signal completion.
import asyncio
import random
async def producer(queue, item_count):
for i in range(item_count):
item = random.randint(1, 100)
await queue.put(item)
print(f"Produced: {item}")
await asyncio.sleep(0.1)
await queue.put(None) # Sentinel to signal end
async def consumer(queue, n…
How to Cancel an asyncio Task with Graceful Cleanup in Python
Cancel a running asyncio task, handle the cancellation signal inside a worker coroutine to perform cleanup, then re-raise so the cancellation propagates correctly.
import asyncio
async def worker(name: str, sleep: float) -> None:
try:
print(f"{name}: starting")
await asyncio.sleep(sleep)
print(f"{name}: completed")
except asyncio.CancelledError:
print(f"{name}: cancelled, cleaning up...")
await asyncio.sleep(0.2) # Simulate clea…
How to 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.
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…
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.
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…
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.
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…
How to Mock asyncio.open_connection in Python
Mock asyncio.open_connection with AsyncMock to test async code without a real network connection.
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_…
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.
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_…
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.
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…
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.
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:
…
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.
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…
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.
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…
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.
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 …
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.
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…
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.
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…
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.
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…
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.
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…
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.
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…
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.
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.…
Distributed tracing with contextvars in Python
Propagate trace and span IDs across function calls using contextvars to mock distributed tracing in a single process.
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…
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.
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…
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
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- Run it in the IDE, tweak values, then take a related quiz or tutorial lesson
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.