Reference library

Python Code Samples

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

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

How to spawn multiple worker processes in Python with multiprocessing.Process

Spawns three separate worker processes using multiprocessing.Process, runs them concurrently, and waits for all to finish before printing a completion message.

multiprocessing parallel concurrency
Python
import multiprocessing
import time

def worker(name):
    print(f"Worker {name} started")
    time.sleep(1)
    print(f"Worker {name} finished")
    return name

if __name__ == "__main__":
    processes = []
    for i in range(3):
        p = multiprocessing.Process(target=worker, args=(i,))
        processes.append(p…
14 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

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.