Reference library

Python Code Samples

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

14 matches
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…
14 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…
15 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

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
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

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.