Reference library

Python Code Samples

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

9 matches
Automation & scripting easy

Check Service Ping Status and Exit Code in Python

Ping a list of hosts, print OK/FAIL per host, and exit with a non-zero code when any host is unreachable.

subprocess ping exit-code
Python
import subprocess
import sys

SERVICES = [
    "8.8.8.8",
    "1.1.1.1",
    "invalid-host",
]

def main():
    failed = []
    for host in SERVICES:
        result = subprocess.run(
            ["ping", "-c", "1", "-W", "2", host],
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
        …
16 0 Open
Reliability & rate limiting easy

Build a Rate Limiter Decorator in Python

This code defines a reusable rate limiter decorator that caps function calls within a sliding time window using a deque and monotonic time.

rate-limiting decorator time
Python
import time
from collections import deque


def rate_limiter(max_calls: int, period: float):
    calls = deque()

    def decorator(func):
        def wrapper(*args, **kwargs):
            now = time.monotonic()
            while calls and now - calls[0] >= period:
                calls.popleft()
            if len(ca…
13 0 Open
Reliability & rate limiting easy

Health Check Mark Unhealthy Stop Traffic Mock in Python

Simulates a health check with a 20% failure rate and automatically stops traffic when the service is unhealthy.

health-check reliability traffic-management
Python
import time
import random

class HealthCheck:
    def __init__(self):
        self.is_healthy = True
        self.stop_traffic = False

    def check_health(self):
        # Simulate health check with random failure rate (20% chance unhealthy)
        self.is_healthy = random.random() > 0.2
        return self.is_heal…
13 0 Open
Reliability & rate limiting easy

How to Implement a Temporary Block in Python

Build a reusable PenaltyBox class that temporarily blocks access after a failure and reports remaining lockout time.

rate-limiting penalty-box lockout
Python
class PenaltyBox:
    def __init__(self, block_seconds: int = 30):
        self.block_seconds = block_seconds
        self._blocked_until = 0.0
        self._attempts = 0

    def try_access(self, current_time: float) -> bool:
        if self._blocked_until and current_time < self._blocked_until:
            return Fa…
14 0 Open
Reliability & rate limiting easy

How to Inject Random Latency for Chaos Testing in Python

Mock unreliable services by wrapping functions with a decorator that adds random network-like delays before execution.

chaos-engineering decorators latency
Python
import random
import time
from functools import wraps

def inject_latency(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        latency = random.uniform(0.1, 0.5)
        print(f"Injecting {latency:.3f}s latency...")
        time.sleep(latency)
        return func(*args, **kwargs)
    return wrapper

@inje…
12 0 Open
Reliability & rate limiting easy

How to Mock Fault Injection Percentage in Python

Simulate a service with a 30% failure rate using random.random to test error handling and retries.

fault-injection random testing
Python
import random

class Service:
    def call(self):
        if random.random() < 0.3:  # 30% failure rate
            raise ConnectionError("Simulated network fault")
        return "ok"

def main():
    svc = Service()
    random.seed(42)  # deterministic for demonstration
    results = []
    for _ in range(10):
     …
14 0 Open
Reliability & rate limiting easy

How to Mock a Slow Startup Probe in Python

Simulate slow service initialization with a configurable mock delay to test readiness probes.

startup probe mock reliability
Python
import time
from dataclasses import dataclass, field


@dataclass
class StartupProbe:
    name: str
    min_wait_sec: float = 0.5
    max_wait_sec: float = 2.0
    _ready: bool = field(default=False, init=False, repr=False)

    def initialize(self) -> None:
        """Simulate slow startup with a fixed mock delay."""…
13 0 Open
Reliability & rate limiting easy

How to Stop Receiving Requests Until Ready in Python

A mock server that refuses requests until a readiness gate is passed, simulating fail-stop behavior for production reliability.

readiness fail-stop mock-server
Python
import random
import time


class MockServer:
    def __init__(self):
        self.ready = False
        self.requests_received = 0

    def readiness_check(self):
        """Simulates a readiness probe. Returns True only when ready."""
        if not self.ready:
            return False
        return True

    def r…
14 0 Open
Reliability & rate limiting easy

Implementing Fallback with Cached Stale Data in Python

This code demonstrates a resilient data-fetching pattern that caches successful responses, falls back to cached data when the external API fails, and returns stale data as a last-resort fallback.

cache fallback resilience
Python
import random
import time

# Simulated cache dictionary: key -> (value, timestamp)
_cache = {}
_CACHE_TTL = 3  # seconds

# Mock data source (simulates an unreliable external API)
def fetch_mock_data(key):
    failure = random.random() < 0.4  # 40% chance of failure
    if failure:
        raise ConnectionError("Mock …
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.