Reference library

Python Code Samples

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

35 matches
Errors & debugging medium

How to Simulate Timeout with Custom TimeoutError in Python

Run a function in a daemon thread and raise a custom TimeoutError if it exceeds a specified time limit.

timeout threading exceptions
Python
import time
from typing import Callable, TypeVar

T = TypeVar("T")


class TimeoutError(Exception):
    """Raised when an operation exceeds its time limit."""

    def __init__(self, message: str = "Operation timed out"):
        self.message = message
        super().__init__(self.message)


def run_with_timeout(func…
12 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
Automation & scripting easy

Stress CPU Threads with a Mock Compute in Python

Simulates CPU-intensive work across multiple threads to test how Python schedules parallel compute.

threading cpu-stress parallelism
Python
import threading
import time


def stress_cpu(iterations: int):
    result = 0
    for i in range(iterations):
        result += i * i % 1000
    return result


def run_mock_stress(thread_count: int, iterations: int):
    threads = []
    for tid in range(thread_count):
        t = threading.Thread(target=lambda: str…
12 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 Demonstrate the GIL with Python Threads vs Processes

Measure and compare wall-clock time for CPU-bound work using Python threads (limited by the GIL) versus multiprocessing (which bypasses the GIL).

gil threading multiprocessing
Python
import threading
import multiprocessing
import time
import os


def cpu_heavy(n):
    return sum(i * i for i in range(n))


def run_threads(n):
    threads = [threading.Thread(target=cpu_heavy, args=(n,)) for _ in range(2)]
    start = time.perf_counter()
    for t in threads:
        t.start()
    for t in threads:
 …
12 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 Speed Up Data Filtering with Python ThreadPoolExecutor

This code compares sequential filtering of even numbers with a threaded version using ThreadPoolExecutor, showing a measurable speedup for I/O-bound work.

threadpoolexecutor concurrency filtering
Python
import time
from concurrent.futures import ThreadPoolExecutor
import random


def is_even(number):
    time.sleep(0.001)  # simulate work
    return number % 2 == 0


def filter_even_sequential(numbers):
    return [n for n in numbers if is_even(n)]


def filter_even_threaded(numbers):
    with ThreadPoolExecutor(max_…
14 0 Open
Concurrency & performance medium

How to Use ThreadPoolExecutor for Concurrent Tasks in Python

Compare sequential execution with ThreadPoolExecutor for I/O-bound tasks, measuring speedup and timing with perf_counter.

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


def fetch_data(index):
    """Simulate a synchronous data fetch."""
    time.sleep(0.1)
    return f"data-{index}"


def run_sequential(total=10):
    """Run tasks one after another."""
    start = time.perf_counter()
    results = [fetch…
14 0 Open
Concurrency & performance medium

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.

threading condition producer-consumer
Python
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:
       …
14 0 Open
Concurrency & performance easy

How to Use threading.Lock to Synchronize a Counter in Python

Safely increment a shared counter across multiple threads using threading.Lock as a mutex to prevent race conditions.

threading lock mutex
Python
import threading

counter = 0
lock = threading.Lock()

def increment():
    global counter
    for _ in range(100000):
        with lock:
            counter += 1

threads = [threading.Thread(target=increment) for _ in range(5)]
for t in threads:
    t.start()
for t in threads:
    t.join()

print(f"Final counter valu…
14 0 Open
Concurrency & performance medium

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.

threading rlock concurrency
Python
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…
14 0 Open
Concurrency & performance medium

How to Use threading.local for Per-Thread Data in Python

Use threading.local to keep thread-specific data — each thread gets its own copy of the attribute, so values don't leak between threads.

threading thread-local concurrency
Python
import threading
import time

local_storage = threading.local()

def worker(name):
    local_storage.name = name
    time.sleep(0.1)
    print(f"Thread {threading.current_thread().name}: {local_storage.name}")

if __name__ == "__main__":
    threads = []
    for i in range(3):
        t = threading.Thread(target=worke…
14 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 start, join, and make daemon threads in Python

Starts one daemon and one non-daemon thread, joins the non-daemon thread, and shows how daemon threads exit when the main program ends.

threading daemon join
Python
import threading
import time
import logging

logging.basicConfig(level=logging.INFO, format="%(threadName)s: %(message)s")

def worker(name, delay):
    for i in range(3):
        time.sleep(delay)
        logging.info(f"{name} step {i}")

if __name__ == "__main__":
    daemon_thread = threading.Thread(
        target…
13 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
Concurrency & performance medium

Thread Pool Map for IO Bound Tasks in Python

Run IO-bound mock tasks concurrently with ThreadPoolExecutor.map and measure total elapsed time in Python.

threading concurrency threadpoolexecutor
Python
import concurrent.futures
import time
from pathlib import Path

def mock_io_task(filename):
    """Simulate an IO-bound task by creating a small file and measuring its latency."""
    path = Path(filename)
    path.write_text("data")
    time.sleep(0.1)  # Simulate slow disk/network
    return f"{filename} written in …
14 0 Open
Concurrency & performance easy

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.

queue threading producer-consumer
Python
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…
12 0 Open
System design patterns medium

How to Limit Concurrent Requests with a Semaphore in Python

Use threading.Semaphore with a ThreadPoolExecutor to cap how many worker threads run simultaneously, preventing resource overload.

concurrency semaphore threading
Python
import threading
import time
from concurrent.futures import ThreadPoolExecutor

def worker(name, semaphore, results):
    with semaphore:
        results.append(f"start {name}")
        time.sleep(0.5)  # simulate async work
        results.append(f"done {name}")

def main():
    sem = threading.Semaphore(2)  # max 2 …
14 0 Open
API design & gRPC medium

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.

api mock-server http
Python
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…
13 0 Open
Streaming & messaging medium

How to Implement Backpressure Pause Producer with a Bounded Queue in Python

Places a Producer thread that sends items into a bounded queue with backpressure: on Full, it pauses to let the consumer catch up.

queues backpressure threading
Python
import threading
import time
import queue
import random


class Producer:
    def __init__(self, q):
        self.q = q
        self.running = True

    def produce(self):
        while self.running:
            item = random.randint(1, 100)
            try:
                self.q.put(item, timeout=0.5)
              …
14 0 Open
Streaming & messaging medium

Simulate RabbitMQ QoS Prefetch Count in Python

Mocks RabbitMQ QoS prefetch semantics using threading and a queue to cap concurrent unacked message processing per worker.

rabbitmq threading qos
Python
import threading
import time
import queue


class RabbitMQMock:
    def __init__(self, prefetch_count=1):
        self.prefetch_count = prefetch_count
        self.channel_queue = queue.Queue()
        self.currently_processing = 0
        self.lock = threading.Lock()

    def start_consuming(self, messages, worker_co…
13 0 Open
Caching & Redis medium

Cache Stampede Prevention with SingleFlight in Python

Implements a SingleFlight pattern in Python to deduplicate concurrent cache-miss computations and prevent cache stampede.

caching concurrency singleflight
Python
import threading
import time
from functools import wraps


class SingleFlight:
    def __init__(self):
        self._lock = threading.Lock()
        self._inflight = None

    def do(self, key, fn):
        with self._lock:
            if self._inflight is not None:
                return self._inflight[1]
           …
15 0 Open
Caching & Redis hard

Coalescing duplicate in-flight requests: one shared result for concurrent callers

Runs identical concurrent requests through a single shared call, caching the result while it's in flight and returning the same value to all callers.

concurrency threading coalescing
Python
import time
import threading
from collections import defaultdict


class CoalescingExecutor:
    def __init__(self):
        self._locks = defaultdict(threading.Lock)
        self._in_flight = {}

    def execute(self, key, func):
        with self._locks[key]:
            if key in self._in_flight:
                re…
15 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.