Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Generate a cloud-init User Data Mock in Python
Generate a cloud-init user data mock for a VM using a dataclass and JSON in Python.
import json
from dataclasses import dataclass, asdict
@dataclass
class VMConfig:
hostname: str
cpus: int
memory_mb: int
ssh_key: str
def generate_cloud_init_mock(config: VMConfig) -> str:
"""Build a cloud-init user-data mock for a VM."""
user_data = {
"hostname": config.hostname,
…
Create a Cloud Storage Helper Class in Python
Build a simple local file-based helper class that mimics cloud storage operations like save, load, and list JSON objects.
import datetime
import json
from pathlib import Path
class CloudDataHelper:
"""Simple helper for reading/writing JSON files in a cloud-style folder."""
def __init__(self, base_dir: str = "cloud_storage"):
self.base_dir = Path(base_dir)
self.base_dir.mkdir(exist_ok=True)
def save_json(se…
Create a Data Helper Class for Beginners in Python
A simple Python class to read and write JSON and CSV files from a local directory, ideal for automating data workflows in cloud environments.
import json
from pathlib import Path
class DataHelper:
"""Simple helper for reading and writing common data files."""
def __init__(self, directory="data"):
self.directory = Path(directory)
self.directory.mkdir(exist_ok=True)
def save_json(self, filename, data):
filepath =…
Exponential Backoff with Jitter for Cloud API Calls in Python
A Python snippet demonstrating exponential backoff with jitter for retrying transient cloud API failures, using a simulated client that has a configurable success rate.
import random
import time
def exponential_backoff_with_jitter(retries=5, base_delay=0.5, max_delay=4.0, jitter_factor=0.3):
for attempt in range(1, retries + 1):
delay = min(max_delay, base_delay * (2 ** (attempt - 1)))
jitter = delay * random.uniform(-jitter_factor, jitter_factor)
effect…
Generate Mock CloudFormation Stack Events in Python
Generate a list of mock AWS CloudFormation stack events with random resources, statuses, and timestamps, and print them as JSON.
import json
import random
from datetime import datetime, timedelta
def generate_mock_stack_events(stack_name="MyTestStack", num_events=10):
"""Generate a list of mock CloudFormation stack events."""
resources = [
("AWS::S3::Bucket", "MyBucket"),
("AWS::EC2::Instance", "MyInstance"),
("…
Generate a Mock Presigned URL in Python with HMAC
Build a mock AWS S3 presigned URL using an HMAC-SHA256 signature, mimicking the core SigV4 pattern without cloud SDK dependencies.
import hashlib
import hmac
import time
import base64
def generate_presigned_url_mock(secret_key, bucket, object_key, expires_in=3600):
# Build the canonical request string (simplified AWS SigV4 style)
timestamp = str(int(time.time()))
expiry = str(int(time.time()) + expires_in)
payload = f"GET\n/{buck…
Generate an Idempotency-Key header mock with UUID in Python
This code provides a mock idempotency service that generates a UUID-based Idempotency-Key header token and validates it, useful for simulating production API behavior in tests.
import uuid
class MockIdempotencyService:
def __init__(self):
self._tokens = {}
def get_token(self, header_name="Idempotency-Key"):
token = str(uuid.uuid4())
self._tokens[header_name] = token
return token
def validate(self, header_name="Idempotency-Key"):
return s…
How to Build a Budget Alert Threshold with Mock Notifications in Python
This code calculates budget usage percentage and triggers a mock alert notification when the usage exceeds a defined threshold.
budget = 500.0
spent = 620.0
alert_threshold = 0.8
def mock_notify(percent_used):
if percent_used >= alert_threshold:
return f"ALERT: Budget usage at {percent_used * 100:.1f}% — over {alert_threshold * 100:.0f}% threshold!"
return f"OK: Budget usage at {percent_used * 100:.1f}% — under threshold."
pe…
How to Build a Multi-Cloud Config Loader with Provider Switching in Python
Load cloud provider configurations (AWS, Azure, GCP) from JSON files using a provider dispatch pattern in Python.
import json
from pathlib import Path
from dataclasses import dataclass
from typing import Dict, Any
@dataclass
class CloudConfig:
provider: str
region: str
settings: Dict[str, Any]
class ConfigLoader:
def __init__(self, config_dir: str = "configs"):
self.config_dir = Path(config_dir)
…
How to Calculate Cloud Cost Estimates with a Python Dictionary
Mocks a cloud pricing calculator using a dictionary of service rates and computes total estimated cost for given service hours.
def estimate_cost(service, hours, rate_table=None):
if rate_table is None:
rate_table = {
"basic": 50,
"standard": 75,
"premium": 100
}
if service not in rate_table:
raise ValueError(f"Unknown service: {service}")
return rate_table[service] * hour…
How to Check an SCP Deny List in Python
Load a JSON SCP policy file, extract the deny_list, and check if a target ARN is denied.
import json
from pathlib import Path
def evaluate_scp_deny_list(policy_path: Path, target_path: str) -> bool:
policy = json.loads(policy_path.read_text())
deny_list = policy.get("deny_list", [])
return target_path in deny_list
if __name__ == "__main__":
policy_file = Path("scp_policy.json")
pol…
How to Convert Python Dict to JSON and Back
Convert Python dictionaries to JSON text and back with a simple helper that serializes and deserializes data structures.
import json
from datetime import datetime, timezone
def convert_data(data, source_format=None, target_format="json"):
"""
Convert Python data structures to txt/json and back.
For beginners: shows how to serialize/deserialize.
"""
if source_format == "json" and target_format == "dict":
ret…
How to Design a Cloud Data Helper Class in Python
A beginner-friendly Python helper class that saves, loads, and aggregates JSON records locally, simulating cloud-style data handling.
import json
from pathlib import Path
from datetime import datetime
class CloudDataHelper:
"""Beginner-friendly helper for working with cloud-based JSON data."""
def __init__(self, base_dir="cloud_data"):
self.base_dir = Path(base_dir)
self.base_dir.mkdir(exist_ok=True)
def save_record(s…
How to Enforce Tag Policies on AWS Resources in Python
Build a reusable Python class that checks AWS resources against a required-tag policy and reports compliance with missing tags.
import json
from dataclasses import dataclass, field
from typing import Dict, List
@dataclass
class Resource:
arn: str
tags: Dict[str, str] = field(default_factory=dict)
class TagPolicyEnforcer:
def __init__(self, required_tags: List[str]):
self.required_tags = set(required_tags)
def enfor…
How to Evaluate Mock NACL Rules in Python
Simulate numbered AWS Network ACL rule evaluation with HMAC integrity checks on request payloads.
import base64
import json
import hmac
import hashlib
def evaluate_mock_rule(rule_number, request_data, secret):
"""
Simulates evaluating an NACL-like numbered rule by:
1. Checking if the rule number exists in the mock policy.
2. Computing an HMAC over the request payload for integrity.
"""
# M…
How to Generate a Mock EKS Kubeconfig in Python
Generate a minimal kubeconfig dict with a mock EKS cluster entry and dump it to YAML using PyYAML.
import yaml
from pathlib import Path
def mock_eks_kubeconfig(cluster_name: str) -> dict:
"""Return a minimal kubeconfig dict with a mock EKS cluster entry."""
return {
"apiVersion": "v1",
"kind": "Config",
"clusters": [
{
"name": f"arn:aws:eks:us-east-1:123…
How to Implement Region Failover Config in Python with Primary and Secondary Mock
This Python class simulates regional failover: it tracks active region, switches to secondary on primary failure, and allows manual recovery.
import time
class RegionFailoverConfig:
def __init__(self, primary, secondary):
self.primary = primary
self.secondary = secondary
self.active = primary
self.failover_count = 0
self.healthy = True
def check_health(self):
"""Mock health check - returns True if ac…
How to Implement Retry with Exponential Backoff for Cloud API 429 Errors in Python
Implement a retry-with-backoff loop in Python to handle 429 throttling errors from cloud APIs, using exponential delay between attempts.
import time
import random
import requests
def api_call(attempt):
"""Mock cloud API that returns 429 for the first two attempts."""
if attempt < 2:
return 429, "Too Many Requests"
return 200, {"data": "success"}
def retry_with_backoff(api_func, max_retries=3, base_delay=0.1):
for attempt in …
How to Mock AWS Secrets Manager in Python
Create a lightweight mock of AWS Secrets Manager's get_secret_value API to test secret retrieval without cloud dependencies.
import json
from typing import Optional
class MockSecretsManager:
"""A simple mock of AWS Secrets Manager's get_secret_value API."""
def __init__(self):
self._secrets: dict[str, str] = {}
def create_secret(self, secret_id: str, secret_value: str) -> None:
"""Store a secret value under a…
How to Mock Auto Scaling Policy Scale Out in Python
Define a mock auto-scaling function that scales out capacity by a factor up to a max, simulating AWS-like events.
def mock_scale_out(current_capacity: int, max_capacity: int, scale_factor: int = 1) -> tuple:
"""
Mock auto-scaling policy: scales out by the specified factor
if capacity allows, capped at max_capacity.
"""
if current_capacity >= max_capacity:
return current_capacity, False
new_cap…
How to Mock Azure Service Bus Queue in Python
A lightweight in-memory mock of the Azure Service Bus queue API for local testing without cloud dependencies.
import json
import time
from collections import deque
class ServiceBusQueueMock:
def __init__(self, queue_name):
self.queue_name = queue_name
self._messages = deque()
self._dead_letter_queue = deque()
self._message_counter = 0
def send_message(self, body, message_id=None, prop…
How to Mock CloudFront Invalidation Paths in Python
Build a sorted, deduplicated list of CloudFront invalidation paths from a set of file paths, adding implicit index.html entries.
import argparse
def build_invalidation_paths(files, include_index=True):
"""
Create CloudFront invalidation paths from a list of files.
Converts file names to root-relative paths and optionally adds /index.html.
"""
paths = []
for f in files:
f = f.strip()
if not f:
…
How to Mock DynamoDB with a Simple Dict Store in Python
A lightweight in-memory DynamoDB mock that stores items in a dict and supports put, get, and query-by-value operations for local testing.
import json
from typing import Any, Dict, Optional
class MockDynamoDB:
def __init__(self) -> None:
self._store: Dict[str, Dict[str, Any]] = {}
def put_item(self, table_name: str, item: Dict[str, Any]) -> None:
key = str(item.get("id"))
if table_name not in self._store:
se…
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…
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.