Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

33 matches
Algorithms & data structures medium

How to Detect Hardcoded Secrets in Python Source Code

A Python utility that scans source code for common hardcoded secrets like API keys, passwords, tokens, and AWS credentials using regex patterns.

secrets regex security
Python
import re

def detect_secrets(text):
    """Detect potential hardcoded secrets in source code."""
    patterns = {
        'api_key': r'(?i)(api[_-]?key|apikey)\s*[=:]\s*["\']([^"\']+)["\']',
        'password': r'(?i)(password|passwd)\s*[=:]\s*["\']([^"\']+)["\']',
        'token': r'(?i)(\b(token|secret)\b)\s*[=:]\s…
42 0 Open
Cloud + Python medium

Cross Account Role Chaining Mock Credentials in Python

Simulate AWS STS AssumeRole with mock credentials for cross-account role chaining in Python.

aws sts mock
Python
import json

class CredentialChain:
    def __init__(self, account_id, role_name):
        self.account_id = account_id
        self.role_name = role_name
        self.credentials = {}

    def assume_role(self, session_name="mock_session"):
        """Simulate STS AssumeRole, returning mock credentials with expiry.""…
16 0 Open
Cloud + Python easy

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.

cloudformation mock aws
Python
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"),
        ("…
15 0 Open
Cloud + Python medium

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.

aws s3 presigned-url
Python
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…
12 0 Open
Cloud + Python easy

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.

cloud config json
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)
      …
12 0 Open
Cloud + Python easy

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.

ipaddress cidr vpc
Python
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…
10 0 Open
Cloud + Python easy

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.

aws scp json
Python
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…
13 0 Open
Cloud + Python easy

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.

aws sts mocking
Python
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",
    …
13 0 Open
Cloud + Python easy

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.

aws tagging compliance
Python
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…
13 0 Open
Cloud + Python medium

How to Evaluate IAM Policy Allow vs Deny in Python

Evaluate an AWS-style IAM policy dict with explicit deny overriding allow and default deny.

iam aws policy-evaluation
Python
import json


def evaluate_policy(action, resource, policy):
    """Evaluate an IAM-like policy dict.
    Explicit deny wins over allow. Default is deny.
    """
    for statement in policy.get("Statement", []):
        effect = statement.get("Effect")
        actions = statement.get("Action", [])
        resources = …
13 0 Open
Cloud + Python easy

How to Evaluate Mock NACL Rules in Python

Simulate numbered AWS Network ACL rule evaluation with HMAC integrity checks on request payloads.

cloud network nacl
Python
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…
16 0 Open
Cloud + Python easy

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.

kubeconfig eks yaml
Python
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…
14 0 Open
Cloud + Python medium

How to Mock AWS SQS Send Receive Delete in Python

Build an in-memory mock of the SQS send, receive, and delete message flow for local testing.

aws sqs mock
Python
import json
from collections import deque
from uuid import uuid4


class MockSQSQueue:
    def __init__(self, name):
        self.name = name
        self._messages = deque()
        self._in_flight = {}

    def send_message(self, body, attributes=None):
        message_id = str(uuid4())
        message = {
         …
13 0 Open
Cloud + Python easy

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.

aws secrets-manager mock
Python
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…
13 0 Open
Cloud + Python easy

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.

auto-scaling cloud simulation
Python
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…
13 0 Open
Cloud + Python easy

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.

cloudfront aws cli
Python
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:
           …
14 0 Open
Cloud + Python easy

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.

elb mock healthcheck
Python
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…
12 0 Open
Cloud + Python medium

How to Mock RDS Snapshot Create and Restore in Python

Mock AWS RDS snapshot creation and restore operations in Python tests using moto and boto3 without hitting real AWS services.

boto3 moto rds
Python
import boto3
from moto import mock_rds


@mock_rds
def create_and_restore_snapshot():
    client = boto3.client("rds", region_name="us-east-1")
    client.create_db_instance(
        DBInstanceIdentifier="my-db",
        DBInstanceClass="db.t3.micro",
        Engine="postgres",
        AllocatedStorage=20,
        Mas…
13 0 Open
Cloud + Python easy

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.

aws lambda api-gateway
Python
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…
12 0 Open
Cloud + Python easy

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.

aws security-groups validation
Python
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…
10 0 Open
Cloud + Python easy

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.

ec2 mock aws
Python
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…
14 0 Open
Cloud + Python medium

How to mock boto3 S3 upload file wrapper in Python

Wrap an S3 put_object call in a testable function that returns metadata, and mock boto3 to verify the upload without touching AWS.

boto3 s3 aws
Python
import boto3
import io


def upload_file_to_s3(file_obj, bucket, key, object_metadata=None):
    """Upload a file-like object to S3 and return a metadata dict."""
    s3 = boto3.client("s3")
    content = file_obj.read()
    s3.put_object(
        Bucket=bucket,
        Key=key,
        Body=content,
        Metadata=…
12 0 Open
Cloud + Python easy

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.

aws spot-instances simulation
Python
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…
12 0 Open
Cloud + Python medium

Mock CDK Synth Output in Python for Template Testing

Simulate AWS CDK synth output with MagicMock to test or preview CloudFormation templates without running a real CDK app.

aws cdk cloudformation
Python
import json
from unittest.mock import MagicMock

def mock_cdk_synth() -> dict:
    """Simulate AWS CDK synth output for a simple S3 bucket."""
    cdk_app = MagicMock()
    cdk_app.synth.return_value.template = {
        "Resources": {
            "MyBucket": {
                "Type": "AWS::S3::Bucket",
              …
11 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.