Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
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"),
("…
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 VPC Subnet CIDR Details in Python
Compute network address, broadcast address, address count, prefix length, and netmask for any IPv4 CIDR using the Python standard library's ipaddress module.
import ipaddress
def subnet_details(cidr: str) -> dict:
network = ipaddress.ip_network(cidr, strict=False)
return {
"network_address": str(network.network_address),
"broadcast_address": str(network.broadcast_address),
"num_addresses": network.num_addresses,
"prefix_length": ne…
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 Create a Mock STS AssumeRole Credentials Dict in Python
Build a realistic AWS STS AssumeRole response dict with temporary credentials, expiry time, and assumed role ARN for local testing.
import json
from datetime import datetime, timedelta, timezone
def mock_sts_credentials(role_arn, session_name, duration=3600):
now = datetime.now(timezone.utc)
expiration = now + timedelta(seconds=duration)
credentials = {
"Credentials": {
"AccessKeyId": "ASIAEXAMPLEACCESSKEY",
…
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 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 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 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 Parse an AWS API Gateway Proxy Event in Python
Extract and parse common fields from a mock API Gateway proxy event, turning the JSON body into a native Python dict.
import json
from typing import Any, Dict, Optional
def parse_proxy_event(event: Dict[str, Any]) -> Dict[str, Any]:
"""Extract and parse common fields from an API Gateway proxy event."""
body = event.get("body", "")
if isinstance(body, str):
body = json.loads(body) if body else {}
elif body is…
How to Validate AWS Security Group Ingress Rules in Python
Validates AWS security group ingress rules (protocol, port ranges, CIDR, description) and returns a list of errors or OK.
from dataclasses import dataclass
from typing import List, Optional
@dataclass
class SecurityGroupRule:
protocol: str
port_range: tuple
cidr: str
description: str = ""
def validate_ingress_rule(rule: SecurityGroupRule) -> List[str]:
"""Validate a security group ingress rule against common AWS pat…
How to mock EC2 describe-instances tag filtering in Python
Simulate AWS EC2 describe-instances with tag-based filtering using a mock dataset and conditional list comprehension.
import json
from datetime import datetime, timezone
def mock_describe_instances(tag_key: str, tag_value: str) -> list[dict]:
"""Simulate EC2 describe-instances with tag filtering."""
all_instances = [
{"InstanceId": "i-0abc123", "State": "running", "Tags": [{"Key": "Name", "Value": "web-server"}, {"K…
Mock AWS Spot Instance Interruption Handler in Python
A Python class that simulates AWS Spot instance interruption checks, handling the 10% chance of termination, logging state-saving, and storing notice details.
import time
import random
class SpotInstanceHandler:
def __init__(self, instance_id):
self.instance_id = instance_id
self.interruption_notices = []
def start(self):
print(f"Spot instance {self.instance_id} started")
def check_interruption(self):
# Simulate random interrup…
Mock CloudWatch put_metric_data in Python
Simulate AWS CloudWatch put_metric_data with validation and formatted output for local testing without AWS.
import json
from datetime import datetime, timezone
def put_metric_data(namespace, metric_data_list):
"""
Mock AWS CloudWatch put_metric_data.
Validates and prints the metrics that would be sent.
"""
timestamp = datetime.now(timezone.utc).isoformat()
print(f"[MockCloudWatch] Received request …
Mock ECS Task Run Stop Status Dict in Python
Build a mock ECS task status dictionary with RUNNING/STOPPED states using the standard library.
from datetime import datetime, timezone
def mock_ecs_task_status(task_id: str, state: str = "RUNNING") -> dict:
"""Return a mock ECS task status dictionary."""
return {
"taskArn": f"arn:aws:ecs:us-east-1:123456789012:task/cluster/{task_id}",
"taskDefinition": "arn:aws:ecs:us-east-1:1234567890…
Mock Lambda handler event context dict in Python
Simulates an AWS Lambda invocation by passing a mock event dict and context object to a handler, then prints the response.
import json
def lambda_handler(event, context):
"""
A mock AWS Lambda handler that processes an event dict and context object.
Demonstrates the typical Lambda function signature and basic event/context usage.
"""
print("Received event:", json.dumps(event, indent=2))
print("Function name:", co…
Mock SNS publish subscribe fanout in Python
Simulates AWS SNS publish/subscribe with an in-memory topic-to-endpoints dict that fans out messages to all subscribers.
class SNSMock:
def __init__(self):
self.topics = {}
def create_topic(self, name):
if name not in self.topics:
self.topics[name] = []
return f"arn:aws:sns:us-east-1:123456789012:{name}"
def subscribe(self, topic_name, endpoint):
self.topics.setdefault(topic_name…
Mock SSM Parameter Store Get Parameters by Path in Python
This code implements a simple mock of the AWS SSM Parameter Store get_parameters_by_path API, returning parameters under a given path with recursive and non-recursive options.
import json
class MockSSM:
def __init__(self, parameters):
self.parameters = parameters
def get_parameters_by_path(self, path, recursive=True):
result = []
for key, value in self.parameters.items():
if recursive:
if key.startswith(path):
…
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.