Reference library

Python Code Samples

Medium snippets you can copy, study, and run in the browser editor.

9 matches
Data pipelines & processing medium

Check Null Rate Threshold in PySpark DataFrame

This PySpark code checks the null rate of specified DataFrame columns against a threshold and returns violations.

pyspark data quality null check
Python
from pyspark.sql import SparkSession
from pyspark.sql.functions import col, sum, count

def check_null_rate(df, threshold=0.2, columns=None):
    """
    Check null rate for specified columns (or all) against a threshold.
    Returns columns that exceed the threshold.
    """
    cols = columns or df.columns
    total…
14 0 Open
Streaming & messaging medium

How to Track Session Windows with Gap Timeout in Python

A Python class that groups events into sessions, closing a session when the gap between events exceeds a timeout threshold.

session-window streaming timeout
Python
import time

class SessionWindow:
    """Track sessions with a gap timeout (mock)."""
    
    def __init__(self, timeout_seconds=5):
        self.timeout = timeout_seconds
        self.session_start = None
        self.last_event_time = None
        self.event_count = 0
        self.events = []
    
    def add_event…
13 0 Open
Reliability & rate limiting medium

Circuit breaker failure threshold count in Python

Track consecutive or time-windowed failures with a deque to open a circuit breaker and auto-recover to half-open after a cooldown.

circuit-breaker resilience deque
Python
from collections import deque
from time import time, sleep


class CircuitBreaker:
    def __init__(self, failure_threshold: int = 5, recovery_time: float = 10.0):
        self.failure_threshold = failure_threshold
        self.recovery_time = recovery_time
        self.failures: deque[float] = deque()
        self.st…
16 0 Open
Reliability & rate limiting medium

Implement a Circuit Breaker Pattern in Python

This code implements a simple circuit breaker that opens after a threshold of consecutive failures, causing subsequent calls to fail fast without invoking the underlying function.

circuit-breaker reliability resilience
Python
class CircuitBreaker:
    def __init__(self, failure_threshold=3):
        self.failure_threshold = failure_threshold
        self.failure_count = 0
        self.open = False

    def call(self, func, *args, **kwargs):
        if self.open:
            raise RuntimeError("Circuit is open - failing fast")
        try:
…
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
Microservices patterns medium

How to implement a circuit breaker in Python

A Python CircuitBreaker class that tracks failures, opens after a threshold, and retries after a timeout.

circuit-breaker resilience microservices
Python
class CircuitBreaker:
    def __init__(self, failure_threshold=3, timeout=5):
        self.failure_threshold = failure_threshold
        self.timeout = timeout
        self.failure_count = 0
        self.last_failure_time = None
        self.state = "CLOSED"

    def call(self, mock_downstream):
        if self.state …
13 0 Open
ML engineering pipelines medium

Detect Concept Drift in Python with a Simple Statistical Test

Detect concept drift by comparing the mean of recent data against a reference distribution using a z-score-like threshold.

concept drift statistics ml monitoring
Python
import random
import statistics

def detect_drift(recent, reference, threshold=1.5):
    ref_mean = statistics.mean(reference)
    ref_std = statistics.stdev(reference)
    
    recent_mean = statistics.mean(recent)
    drift_score = abs(recent_mean - ref_mean) / (ref_std if ref_std > 0 else 1)
    
    drifted = drif…
15 0 Open
Database scaling & optimization medium

How to Mock a Hot Shard Split in Python

Simulate a database hot shard splitting into two shards by key ranges when it exceeds a threshold, with a mock class for testing.

sharding databases mock
Python
import random
from collections import defaultdict


class HotShardMock:
    """Mock implementation of a hot shard split in a distributed database."""

    def __init__(self, shard_id="shard_1", max_entries=5):
        self.shard_id = shard_id
        self.max_entries = max_entries
        self.entries = {}

    def ad…
16 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.