Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
How to Mock ELB Target Health Status in Python
Simulate AWS Elastic Load Balancer target health checks with a Python dict that mutates status and healthy host counts.
from random import randint
def elb_target_mock_status(target_id, healthy=True):
targets = {
1: {"Id": "i-001", "Status": "healthy", "Port": 80, "HealthyHostCount": 1},
2: {"Id": "i-002", "Status": "unhealthy", "Port": 80, "HealthyHostCount": 0},
3: {"Id": "i-003", "Status": "healthy", "Por…
How to Build a Health Check System with Instance Up and Down Status in Python
Track instance health by marking them up or down and simulating health checks with a mock class in Python.
from datetime import datetime
import random
class HealthChecker:
def __init__(self):
self.status = {}
def mark_up(self, instance_id):
self.status[instance_id] = {
"state": "up",
"last_check": datetime.now().isoformat(),
"healthy": True
}
…
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.
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…
How to Create a Deep Health Check Database in Python
Setup a SQLite-backed health check database, insert mock data with response times and statuses, and generate a report ordered by most recent check.
import sqlite3
from datetime import datetime, timedelta
from pathlib import Path
DB_PATH = Path("deep_health_check.db")
def setup_database():
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS health_checks (
id INTEGER PRIMARY KEY AU…
Mock Health Endpoint Liveness Check in Python
Simulate a liveness endpoint that reports service health with a configurable failure rate and uptime.
import time
import random
def liveness_check(service_name: str, failure_rate: float = 0.1) -> dict:
"""Mock health check that returns liveness status with a configurable failure rate."""
healthy = random.random() > failure_rate
response = {
"service": service_name,
"status": "alive" if he…
How to Build a Health Check Service Registry in Python
Build a minimal Python service registry that handles registration, deregistration, health checks, and service listing in one simple class.
import random
import time
class ServiceRegistry:
def __init__(self):
self.services = {}
def register(self, name, address):
self.services[name] = {
"address": address,
"status": "healthy",
"registered_at": time.time(),
"checks": 0
}
…
How to Mock a Dependency for Readiness Probe in Python
Use unittest.mock.Mock to simulate a dependency's readiness check response for testing a service's is_ready method without hitting a real connection.
import time
import unittest
from unittest.mock import Mock
class Service:
def __init__(self, dependency):
self.dependency = dependency
def is_ready(self):
try:
result = self.dependency.check()
return result == "ready"
except Exception:
return False
…
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
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- 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.