Reference library

Python Code Samples

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

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

How to Signal asyncio Workers to Stop with an Event in Python

Use an asyncio.Event to coordinate graceful shutdown of multiple concurrent worker tasks in Python.

asyncio events concurrency
Python
import asyncio
import random

async def worker(name, stop_event):
    while not stop_event.is_set():
        await asyncio.sleep(random.uniform(0.1, 0.5))
        print(f"Worker {name} processing...")
    print(f"Worker {name} stopped.")

async def main():
    stop_event = asyncio.Event()
    workers = [asyncio.create…
11 0 Open
Observability & SRE medium

How to Build an HTTP Server Request Duration Histogram in Python

Create a small HTTP server that times each GET request, buckets the duration, and prints a histogram on shutdown.

http.server histogram performance
Python
import time
import random
from collections import Counter
from http.server import HTTPServer, BaseHTTPRequestHandler


class HistogramHandler(BaseHTTPRequestHandler):
    response_times = Counter()

    def do_GET(self):
        start = time.perf_counter()
        time.sleep(random.uniform(0.001, 0.1))
        duratio…
13 0 Open
Observability & SRE easy

How to Flush Metrics on Graceful Shutdown in Python

Register an atexit handler to automatically flush collected metrics when a Python process exits gracefully.

atexit metrics graceful-shutdown
Python
import atexit
import time
import random


class MetricsCollector:
    def __init__(self):
        self._metrics = []
        atexit.register(self.flush)

    def record(self, name, value):
        self._metrics.append((name, value, time.time()))

    def flush(self):
        print(f"Flushing {len(self._metrics)} metri…
14 0 Open
Production deployment patterns medium

How to Drain a Connection Pool Before Exit in Python

Gracefully close all pooled sockets using a thread-safe ConnectionPool that drains connections before program exit.

connection-pool sockets threading
Python
import socket
import threading
import time
import random

class ConnectionPool:
    def __init__(self, size=5):
        self.pool = []
        self.lock = threading.Lock()
        self.closed = False
        for _ in range(size):
            self.pool.append(self.create_connection())
    
    def create_connection(sel…
13 0 Open
Production deployment patterns easy

How to Mock a SIGTERM Handler in Python

Create a graceful shutdown handler for SIGTERM and SIGINT signals, then test it by simulating a signal delivery without terminating the process.

signals graceful-shutdown sigterm
Python
import signal
import time

class Service:
    def __init__(self):
        self.running = True

    def shutdown(self, signum, frame):
        print(f"Received signal {signum}, shutting down gracefully...")
        self.running = False

    def run(self):
        signal.signal(signal.SIGTERM, self.shutdown)
        sig…
13 0 Open
Production deployment patterns easy

How to Mock time.sleep in a Python PreStop Hook

This code simulates a Kubernetes PreStop hook that delays shutdown, then mocks time.sleep to verify the hook logic without real delay.

mocking prestop kubernetes
Python
import subprocess
import sys
import time
from unittest.mock import patch

def pre_stop_hook():
    """Simulate a Kubernetes PreStop hook that sleeps before shutdown."""
    print("PreStop hook started: delaying shutdown")
    time.sleep(3)
    print("PreStop hook completed: ready to shutdown")

if __name__ == "__main_…
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.