Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

70 matches
Strings & text easy

How to Format a Float as Currency in Python

This code defines a function that converts a float to a string formatted as US currency with two decimal places and comma separators.

formatting currency f-string
Python
def format_currency(amount):
    return f"${amount:,.2f}"

if __name__ == "__main__":
    test_amounts = [1234.5, 0, 9999999.999, -42.867]
    for amount in test_amounts:
        print(f"{amount} -> {format_currency(amount)}")
13 0 Open
Errors & debugging easy

How to define an exception hierarchy for domain errors in Python

Create a custom exception hierarchy with a base DomainError class and specific subclasses to handle validation, not-found, permission, and concurrency errors cleanly in Python apps.

exceptions domain-errors error-handling
Python
class DomainError(Exception):
    """Base class for all domain errors."""
    pass

class ValidationError(DomainError):
    """Raised when input data fails validation rules."""
    pass

class NotFoundError(DomainError):
    """Raised when a requested entity does not exist."""
    pass

class PermissionDeniedError(Dom…
14 0 Open
Files & data medium

How to Use fcntl for Exclusive File Locking in Python

This code demonstrates how to acquire an exclusive advisory lock on a file using fcntl.flock with a non-blocking flag, simulate work, then release the lock.

fcntl file-locking flock
Python
import fcntl
import os
import tempfile
import time

def acquire_exclusive_lock(filepath):
    fd = os.open(filepath, os.O_RDWR | os.O_CREAT)
    try:
        fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
        print(f"Exclusive lock acquired on {filepath}")
        time.sleep(1)  # Simulate work while holding the l…
12 0 Open
OOP & classes easy

How to Create an Immutable Money Class in Python with dataclasses

Define a frozen dataclass Money that holds an amount and currency, enforces non-negative amounts, and supports safe addition across matching currencies.

dataclass immutable money
Python
from dataclasses import dataclass


@dataclass(frozen=True)
class Money:
    amount: float
    currency: str = "USD"

    def __post_init__(self) -> None:
        if self.amount < 0:
            raise ValueError("amount must be non-negative")

    def add(self, other: "Money") -> "Money":
        if self.currency != o…
16 0 Open
AI & LLM integration patterns medium

How to parallel map embeddings with a thread pool in Python

Run embedding computations in parallel using ThreadPoolExecutor, collect results into a dict keyed by the original item.

concurrency threadpool embeddings
Python
import threading
from concurrent.futures import ThreadPoolExecutor
import time


def compute_embedding(item: int) -> tuple[int, int]:
    time.sleep(0.05)  # Simulate embedding work
    return item, item * 10


def parallel_map_embed(items, max_workers=3):
    results = {}
    with ThreadPoolExecutor(max_workers=max_w…
15 0 Open
Automation & scripting medium

Find Broken Image References Across a Website in Python

Crawl internal pages of a website, collect all image source URLs, then check each with HEAD requests to report any that return HTTP 4xx or connection errors.

web scraping crawling broken links
Python
import requests
from urllib.parse import urljoin, urlparse
from bs4 import BeautifulSoup
from concurrent.futures import ThreadPoolExecutor, as_completed

def find_all_links(base_url, max_pages=50):
    visited, to_visit = set(), {base_url}
    while to_visit and len(visited) < max_pages:
        url = to_visit.pop()
 …
37 0 Open
Automation & scripting medium

How to Build a Cryptocurrency Price Tracker in Python

A continuous Python script that fetches real-time cryptocurrency prices from the CoinGecko API and displays them on a loop.

crypto api automation
Python
import requests
import time

def get_crypto_prices(coin_ids=["bitcoin", "ethereum", "solana"]):
    url = "https://api.coingecko.com/api/v3/simple/price"
    params = {
        "ids": ",".join(coin_ids),
        "vs_currencies": "usd"
    }
    try:
        response = requests.get(url, params=params, timeout=10)
     …
44 0 Open
Automation & scripting easy

How to Check Website Status Codes in Python

This script checks the HTTP status codes of multiple URLs concurrently using a thread pool and prints the results.

requests threading http-status
Python
import requests
from concurrent.futures import ThreadPoolExecutor

URLS = [
    "https://www.google.com",
    "https://www.python.org",
    "https://www.nonexistent-site-12345.com",
    "https://www.github.com",
]

def check_status(url):
    try:
        response = requests.get(url, timeout=5)
        return url, resp…
11 0 Open
Data pipelines & processing easy

Parallel Extract Multiple Sources with Threads in Python

Extract data from multiple sources in parallel using ThreadPoolExecutor and verify results match sequential processing.

threads threadpoolexecutor concurrency
Python
import threading
from concurrent.futures import ThreadPoolExecutor

def extract_from_source(source):
    """Simulate extracting data from a source."""
    return f"Data from {source}"

def main():
    sources = ["source_a", "source_b", "source_c", "source_d"]
    
    # Sequential extraction for comparison
    sequent…
14 0 Open
Concurrency & performance medium

Graceful Shutdown Executor Context Manager in Python

A context manager that starts a background thread and ensures it stops gracefully on exit, handling timeouts and exceptions.

threading context-manager graceful-shutdown
Python
import signal
import threading
import time
from contextlib import contextmanager


@contextmanager
def graceful_shutdown_executor(timeout=5.0):
    """Context manager that runs a task and gracefully stops it on timeout or exception."""
    stop_event = threading.Event()

    def task():
        print("Task started")
 …
15 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 easy

How to Convert Data in Parallel with ThreadPoolExecutor in Python

This example demonstrates converting a list of items in parallel using ThreadPoolExecutor, showing performance gains over serial processing.

concurrency threadpoolexecutor parallelism
Python
import time
from concurrent.futures import ThreadPoolExecutor


def convert_data(item):
    """Simulate a CPU/IO-bound conversion task."""
    time.sleep(0.05)  # simulate work
    return item.upper()


if __name__ == "__main__":
    items = [f"item_{i}" for i in range(20)]

    start = time.perf_counter()
    serial_…
15 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 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 medium

How to Parse JSON Files in Parallel with Python ThreadPoolExecutor

Load and transform JSON records from multiple files concurrently using ThreadPoolExecutor for faster I/O-bound parsing.

threadpool json concurrency
Python
import time
from concurrent.futures import ThreadPoolExecutor
import json

def load_json_file(path):
    with open(path, 'r') as f:
        return json.load(f)

def transform_record(record):
    record['full_name'] = f"{record.pop('first_name', '')} {record.pop('last_name', '')}".strip()
    record['score'] = int(reco…
16 0 Open
Concurrency & performance medium

How to Pause and Resume Threads with threading.Event in Python

Use threading.Event to pause and resume worker threads in Python, controlling execution flow with set and clear methods.

threading events concurrency
Python
import threading
import time

workers = []

def worker(name, event):
    for i in range(10):
        event.wait()
        print(f"{name} step {i}")
        time.sleep(0.1)

def pause_worker(name):
    global pause_event
    for w in workers:
        if w.name == name:
            pause_event.clear()
            print(…
10 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 easy

How to Send and Receive Messages Between Processes with multiprocessing.Pipe in Python

Use multiprocessing.Pipe to create a two-way connection between two processes, send a message from parent to child, and receive a reply back.

multiprocessing pipe interprocess-communication
Python
import multiprocessing


def child_process(conn):
    """Receive from parent and send back a response."""
    message = conn.recv()
    print(f"Child received: {message}")
    conn.send("Hello from child!")


if __name__ == "__main__":
    parent_conn, child_conn = multiprocessing.Pipe()

    process = multiprocessing…
14 0 Open
Concurrency & performance medium

How to Share Memory Between Processes in Python with multiprocessing.Value and Array

Share a numeric value and a list-like array across multiple Python processes using multiprocessing.Value and multiprocessing.Array, with each process modifying the same memory.

multiprocessing shared-memory concurrency
Python
import multiprocessing

def worker(shared_value, shared_array, index):
    shared_value.value += 10
    shared_array[index] = shared_array[index] * 2

if __name__ == "__main__":
    shared_value = multiprocessing.Value("i", 5)
    shared_array = multiprocessing.Array("i", [1, 2, 3, 4, 5])

    processes = []
    for i…
13 0 Open
Concurrency & performance medium

How to Share a Dict and List Between Processes with multiprocessing Manager in Python

This code demonstrates how to share a dictionary and a list between multiple processes using multiprocessing.Manager, enabling safe concurrent updates.

multiprocessing manager shared-state
Python
import multiprocessing as mp


def worker(shared_dict, shared_list, name):
    shared_dict[name] = name.upper()
    shared_list.append(name)
    print(f"{name} added to shared structures")


def main():
    with mp.Manager() as manager:
        shared_dict = manager.dict()
        shared_list = manager.list()

       …
13 0 Open
Concurrency & performance medium

How to Share a Queue Between Processes in Python

Use multiprocessing.Queue to pass work from a producer process to multiple consumer processes, coordinating with a sentinel stop message.

multiprocessing queue concurrency
Python
import multiprocessing
import time


def producer(queue, items):
    for item in items:
        queue.put(item)
        time.sleep(0.1)
    queue.put("STOP")


def consumer(queue, name):
    while True:
        item = queue.get()
        if item == "STOP":
            break
        print(f"{name} processed: {item}")

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