Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
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…
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.
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(*…
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.
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…
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.
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())
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…
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.
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 …
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.
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_…
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.
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…
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…
asyncio sleep cooperative scheduling demo in Python
This demo shows how asyncio.sleep yields control between concurrent tasks, letting multiple workers interleave their ticks.
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…
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 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.
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() …
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 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.
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 …
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 Compose Parallel API Calls in Python with asyncio.gather
Compose multiple mock API responses in parallel using asyncio.gather with per-service simulated latency.
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),
…
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.
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…
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.