Reference library

Python Code Samples

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

44 matches
Reliability & rate limiting easy

How to implement rate limiting in Python

Build a simple sliding-window rate limiter in Python that enforces a max number of calls per time period and formats data with timestamps.

rate-limiting time sliding-window
Python
import time

class RateLimiter:
    def __init__(self, max_calls, period):
        self.max_calls = max_calls
        self.period = period
        self.calls = []
    
    def allow(self):
        now = time.time()
        # Remove calls older than the period window
        self.calls = [t for t in self.calls if now -…
17 0 Open
Reliability & rate limiting medium

How to implement rate limiting per API key in Python

A simple sliding-window rate limiter that tracks request timestamps per API key and rejects requests exceeding the configured limit.

rate-limiting api time-window
Python
import time

API_RATE_LIMITS = {"api_key_1": 5, "api_key_2": 3}  # max requests per window
WINDOW_SECONDS = 10

class RateLimiter:
    def __init__(self, limits, window):
        self.limits = limits
        self.window = window
        self.requests = {key: [] for key in limits}

    def allow(self, api_key):
       …
13 0 Open
Reliability & rate limiting easy

Rate Limit per User ID in Python with a Dict Mock

Implements a simple sliding window rate limiter using a defaultdict of timestamps per user ID, blocking requests that exceed a max count within a time window.

rate-limiting defaultdict sliding-window
Python
import time
from collections import defaultdict


class RateLimiter:
    def __init__(self, max_requests, window_seconds):
        self.max_requests = max_requests
        self.window_seconds = window_seconds
        self.user_timestamps = defaultdict(list)

    def allow_request(self, user_id):
        now = time.tim…
14 0 Open
Reliability & rate limiting easy

Rate Limiting in Python with a Sliding Window

A beginner-friendly dataclass-based sliding window rate limiter that controls how many calls are allowed per time window.

rate-limiting sliding-window dataclass
Python
import time
from dataclasses import dataclass


@dataclass
class RateLimiter:
    max_calls: int
    window_seconds: float = 1.0

    def __post_init__(self):
        self.calls = []
        self._start = time.monotonic()

    def _update(self, now):
        self.calls = [t for t in self.calls if now - t < self.window…
12 0 Open
Reliability & rate limiting easy

Rate Limiting with a Simple Python RateLimiter Class

A beginner-friendly Python rate limiter that tracks call timestamps and enforces a maximum number of calls within a rolling time window, with a helper to validate positive integers.

rate-limiting time api
Python
import time

class RateLimiter:
    def __init__(self, max_calls, period_seconds):
        self.max_calls = max_calls
        self.period_seconds = period_seconds
        self.calls = []

    def is_allowed(self):
        now = time.time()
        while self.calls and now - self.calls[0] >= self.period_seconds:
      …
13 0 Open
Observability & SRE easy

Calculate Error Rate from Log Stream in Python

Parses a mock log stream to count errors and compute the error percentage using a rolling window of recent entries.

logging regex error-rate
Python
import re
from collections import deque

def error_rate_from_log_stream(message):
    log_pattern = r'^\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\] (ERROR|INFO|DEBUG): (.*)$'
    recent_entries = deque(maxlen=100)
    error_count = 0
    total_count = 0

    for line in message.strip().split('\n'):
        match = re.mat…
15 0 Open
Observability & SRE easy

Check if a Timestamp Falls in a Daily Maintenance Window in Python

A small Python function that returns True when a datetime falls inside a daily maintenance window, and a demo printing yes/no for sample timestamps.

maintenance datetime scheduling
Python
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo


def in_maintenance_window(now: datetime, start_hour: int = 2, duration_hours: int = 4) -> bool:
    """Return True if 'now' falls inside the daily maintenance window."""
    day_start = now.replace(hour=start_hour, minute=0, second=0, microsecond…
15 0 Open
Observability & SRE medium

How to Build a Burn Rate Alert with Multiple Time Windows in Python

Track token consumption and trigger alerts when the burn rate exceeds a threshold across multiple time windows using deque and time-based sliding windows.

burn-rate alerts time-windows
Python
import time
from collections import deque

class BurnRateAlert:
    def __init__(self, windows_seconds=(60, 300, 900), threshold_rate=0.8):
        self.windows = {w: deque() for w in windows_seconds}
        self.threshold_rate = threshold_rate
        self.previous_tokens = None

    def record_sample(self, current_…
16 0 Open
Observability & SRE easy

How to Compute SRE Metrics Like Error Rate and Availability in Python

Tracks log events in a sliding time window and calculates error rate per second and availability percentage using an easy-to-follow class.

observability sre metrics
Python
from collections import deque
from datetime import datetime, timedelta
from typing import Dict, Deque


class LogMetrics:
    """Simple observability helper to track log events and calculate SRE metrics."""

    def __init__(self, window_seconds: int = 60):
        self.window_seconds = window_seconds
        self.eve…
14 0 Open
Observability & SRE medium

How to Create a StatsD UDP Metric Mock Server in Python

Run a lightweight mock UDP server that captures StatsD metrics over a short window for local testing.

statsd udp sockets
Python
import socket
import threading
import time


def start_mock_statsd_server(host="127.0.0.1", port=8125, timeout=3):
    """Run a mock StatsD UDP server that captures metrics for a short window."""
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind((host, port))
    sock.settimeout(timeout)
    me…
13 0 Open
Observability & SRE medium

How to Group Alerts by Time Window in Python

Group alert occurrences that fall within a sliding time window per alert key, reducing noise and summarizing bursts into single events.

alerts grouping monitoring
Python
from collections import defaultdict
from datetime import datetime, timedelta

def group_alerts(alerts, window_minutes=10):
    """Group alerts that occur within the same time window."""
    alerts_by_key = defaultdict(list)
    
    for alert in alerts:
        key = alert["key"]
        timestamp = alert["timestamp"]…
12 0 Open
Observability & SRE easy

How to mock Prometheus alert rule thresholds in Python

Simulate a Prometheus alert rule with a configurable threshold and duration window, firing only when the metric exceeds the threshold long enough.

prometheus alerting sre
Python
import time
import random


class MetricsStore:
    def __init__(self):
        self.metrics = {}

    def set_metric(self, name, value, labels=None):
        key = (name, tuple(sorted((labels or {}).items())))
        self.metrics[key] = value

    def get_metric(self, name, labels=None):
        key = (name, tuple(s…
14 0 Open
Big data & Spark medium

How to Implement a Streaming Watermark in Python

Mock structured streaming watermarks in Python to track late event times and compute a watermark for windowed processing.

streaming watermark spark
Python
from datetime import datetime, timedelta
import time

class StreamingWatermark:
    """Mock watermark tracker for structured streaming."""

    def __init__(self, watermark_delay_seconds):
        self.watermark_delay = timedelta(seconds=watermark_delay_seconds)
        self.max_event_time = None

    def observe_even…
14 0 Open
Big data & Spark medium

How to Implement row_number Window Function in Python

This code implements a SQL-style ROW_NUMBER() window function in pure Python, partitioning rows by a set of columns and ranking them within each partition by an ordered set of columns.

window-functions data-processing row-number
Python
from collections import defaultdict
import itertools


def row_number(rows, partition_by, order_by):
    partitions = defaultdict(list)
    for index, row in enumerate(rows):
        key = tuple(row[col] for col in partition_by)
        partitions[key].append((index, row))

    result = []
    for key in partitions:
 …
17 0 Open
Big data & Spark medium

How to Mock and Test a Rate-Limited Source Stream in Python

Build a class that rate-limits emitted items using a sliding window and test it with a simulated stream in Python.

rate-limiting mock-testing streaming
Python
import time
from collections import deque


class RateLimitedSource:
    def __init__(self, max_rate, window=1.0):
        self.max_rate = max_rate
        self.window = window
        self._timestamps = deque()

    def emit(self, item):
        now = time.monotonic()
        while self._timestamps and self._timestam…
16 0 Open
Big data & Spark medium

How to implement a tumbling window aggregation in Python

Build a mock tumbling window aggregator in Python that groups streaming events into fixed time intervals and computes count, sum, and average per window.

tumbling-window streaming aggregation
Python
import time
from collections import deque

class TumblingWindow:
    def __init__(self, duration_seconds):
        self.duration = duration_seconds
        self.buffer = deque()
        self.window_start = None

    def add(self, item):
        current_time = time.time()
        if self.window_start is None:
         …
13 0 Open
Big data & Spark easy

Session window gap mock in Python

Group sorted timestamps into sessions where any gap between consecutive events exceeds a threshold starts a new session.

timestamps sessions windowing
Python
from datetime import datetime, timedelta


def session_windows(timestamps, gap_seconds=300):
    """Group timestamps into sessions where gaps > gap_seconds start new sessions."""
    if not timestamps:
        return []

    # Sort timestamps chronologically to ensure correct windowing
    timestamps = sorted(timestam…
14 0 Open
Big data & Spark easy

Sliding Window Streaming Mock in Python

A simple Python class that maintains a sliding window of recent streaming values and computes the running average.

streaming sliding-window averages
Python
import time
import random

class StreamingMock:
    """Produces a stream of numbers using a sliding window."""
    
    def __init__(self, window_size=5):
        self.window = []
        self.window_size = window_size
        
    def push(self, value):
        """Add a value, sliding the window forward."""
        s…
12 0 Open
Database scaling & optimization easy

How to Mock Date Sharding by Range in Python

Split a date interval into fixed-size contiguous shards, returning each window as an ISO date string pair.

date datetime sharding
Python
from datetime import date, timedelta

def shard_ranges(start_date, end_date, shard_days=7):
    if start_date > end_date:
        raise ValueError("start_date cannot be after end_date")

    shards = []
    current = start_date
    while current <= end_date:
        shard_end = min(current + timedelta(days=shard_days …
13 0 Open
Production deployment patterns medium

Auto Rollback on Error Rate Exceeded in Python

Simulate a service that monitors a rolling window of request errors and automatically rolls back when the error rate exceeds a threshold.

error-rate rollback rolling-window
Python
import random
import time


def simulate_requests(total_requests=1000, rollback_threshold=0.2):
    """
    Simulate a service that automatically rolls back when the error rate
    exceeds a threshold within a rolling window.
    """
    window_size = 100
    errors_seen = []
    rolled_back = False

    for req_num i…
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.