Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
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 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 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 …
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.