Reference library

Python Code Samples

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

10 matches
Observability & SRE easy

Generate Synthetic SRE Metrics and Calculate Availability in Python

Create realistic service metrics with random latency, error rate, and request counts, then compute availability and summarize the stream for SLO checks.

sre synthetic-data metrics
Python
from datetime import datetime, timedelta
import random

def generate_service_metrics(service_name: str, minutes: int = 30) -> list[dict]:
    """Generate synthetic SRE metrics for a service across recent minutes."""
    metrics = []
    now = datetime.now()
    
    for i in range(minutes):
        timestamp = now - t…
14 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 Calculate Apdex Score from Latency Data in Python

Generate simulated latency samples and compute the Apdex score to gauge user satisfaction with an application's performance.

apdex latency observability
Python
import random
import statistics

def generate_latencies(count=100, base=100, stddev=30):
    return [max(0, random.gauss(base, stddev)) for _ in range(count)]

def apdex(latencies, threshold=200):
    satisfied = sum(1 for lat in latencies if lat < threshold)
    tolerating = sum(1 for lat in latencies if lat >= thres…
15 0 Open
Observability & SRE easy

How to Check Service Readiness Dependencies in Python

This code simulates a readiness check for external dependencies (database, cache, queue) with mock availability data and reports readiness status.

readiness dependencies health-check
Python
import sys
from datetime import datetime


def check_dependencies(config):
    results = []
    for dep, required in config.items():
        available = mock_availability(dep)
        status = "READY" if available >= required else "NOT READY"
        results.append((dep, available, required, status))
    return result…
11 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 Implement an Error Budget Policy in Python

This code implements a mock error budget policy that decides whether to freeze deployments based on a simulated error rate and monthly freeze limits.

error-budget sre deploy-freeze
Python
from datetime import datetime, timedelta

class ErrorBudgetPolicy:
    FREEZE_WINDOW_HOURS = 24
    MAX_FREEZES_PER_MONTH = 3

    def __init__(self, budget_percentage=99.9):
        self.budget_percentage = budget_percentage
        self.freeze_count = 0
        self.last_freeze_start = None
        self.freeze_enabl…
13 0 Open
Observability & SRE easy

How to Process System Metrics (RSS, CPU) in Python

Simulate and aggregate RSS and CPU system metrics to compute averages and maximums for monitoring dashboards.

metrics rss cpu
Python
import random
import time
from collections import namedtuple

Metric = namedtuple("Metric", ["name", "value", "unit"])


def generate_metrics(num_metrics: int = 5) -> list:
    """Simulate a batch of system metrics."""
    metrics = []
    for i in range(num_metrics):
        rss = random.randint(50, 500)  # MB
      …
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
Observability & SRE easy

How to mock SLI availability success ratio in Python

Simulate request outcomes with deterministic randomness and compute the SLI availability success ratio to check if a target is met.

sli availability monitoring
Python
import random
from collections import defaultdict

def mock_availability(num_requests=1000, target_ratio=0.995):
    """
    Simulate request outcomes and compute the SLI availability success ratio.
    
    Args:
        num_requests: Total number of requests to simulate
        target_ratio: Target availability rati…
14 0 Open
Observability & SRE easy

Track Success Rates and Latency in Python: SRE Metrics Helper

A beginner-friendly Python class to record request outcomes and latencies, then report success rate, average latency, and p99.

sre metrics latency
Python
import random
import time
from collections import defaultdict


class MetricsTracker:
    """Simple helper to track success rates and latencies for SRE beginners."""

    def __init__(self):
        self.successes = 0
        self.failures = 0
        self.latencies = []

    def record(self, success, latency_ms):
   …
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.