Reference library

Python Code Samples

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

10 matches
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",
    …
14 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…
14 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…
11 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…
15 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=…
13 0 Open
Cloud + Python medium

How to mock boto3 S3 upload in Python

Shows how to mock the boto3 S3 client with unit tests and wrap an upload function to return a dictionary with status details.

boto3 s3 mocking
Python
import boto3
from unittest.mock import Mock, patch

class S3Uploader:
    def __init__(self, bucket_name):
        self.bucket_name = bucket_name
        self.s3 = boto3.client("s3", region_name="us-east-1")

    def upload_file(self, local_path, s3_key):
        self.s3.upload_file(local_path, self.bucket_name, s3_ke…
12 0 Open
Cloud + Python easy

Mock CloudWatch put_metric_data in Python

Simulate AWS CloudWatch put_metric_data with validation and formatted output for local testing without AWS.

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

Mock Route53 change_resource_record_sets in Python

This code demonstrates how to mock AWS Route53 change_resource_record_sets API calls using the botocore Stubber, allowing you to test DNS update logic without touching real infrastructure.

aws route53 boto3
Python
import boto3
from botocore.exceptions import ClientError

def mock_change_resource_record_sets():
    """Demonstrates Route53 change_resource_record_sets with a mock client."""
    # Create a mock Route53 client
    route53 = boto3.client('route53', region_name='us-east-1', 
                          aws_access_key_id…
14 0 Open
Cloud + Python medium

Mock S3 List Objects Paginator in Python

This code implements a mock S3 paginator that yields pages of object keys, mimicking the behavior of boto3's list_objects_v2 paginator for local testing.

s3 mock paginator
Python
import json
from datetime import datetime, timezone


class MockS3Paginator:
    """A mock S3 list_objects_v2 paginator returning pages of keys."""

    def __init__(self, bucket, all_keys, page_size=1000):
        self.bucket = bucket
        self.all_keys = all_keys
        self.page_size = page_size

    def pagina…
13 0 Open
Production deployment patterns medium

How to mock S3 remote backend for Terraform in Python

Simulate a Terraform S3 remote backend using moto to write and read state files, enabling local testing without real AWS.

boto3 moto terraform
Python
import boto3
from moto import mock_aws
import json
from pathlib import Path

@mock_aws
def demo_s3_remote_backend():
    s3 = boto3.client("s3", region_name="us-east-1")
    bucket = "terraform-state-bucket"
    key = "env/prod/terraform.tfstate"
    
    s3.create_bucket(Bucket=bucket)
    
    # Simulate Terraform w…
14 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.