Type annotations for boto3 S3

1.42.85 · active · verified Thu Apr 09

This library provides PEP 561 compliant type annotations (stub files) for the `boto3` S3 service, generated by `mypy-boto3-builder`. It enhances static analysis, auto-completion, and type checking in IDEs and tools like `mypy` for code interacting with AWS S3 via `boto3`, addressing the dynamic nature of `boto3` clients and resources.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `types-boto3-s3` to add type hints to a `boto3` S3 client. The `TYPE_CHECKING` guard ensures that the type stubs are only imported during static analysis, preventing unnecessary runtime dependencies. It initializes an S3 client and lists bucket names, with all relevant variables type-hinted for better code quality and IDE support.

import boto3
from typing import TYPE_CHECKING

# Only import type stubs during type checking to avoid runtime dependency
if TYPE_CHECKING:
    from types_boto3_s3.client import S3Client
    from types_boto3_s3.type_defs import ListBucketsOutputTypeDef

def list_s3_bucket_names() -> list[str]:
    # The actual boto3 client is used at runtime
    s3_client: 'S3Client' = boto3.client(
        "s3",
        aws_access_key_id=os.environ.get('AWS_ACCESS_KEY_ID', ''),
        aws_secret_access_key=os.environ.get('AWS_SECRET_ACCESS_KEY', ''),
        region_name=os.environ.get('AWS_REGION', 'us-east-1')
    )

    print("Listing S3 buckets...")
    response: 'ListBucketsOutputTypeDef' = s3_client.list_buckets()
    bucket_names = [bucket['Name'] for bucket in response.get('Buckets', [])]
    return bucket_names

if __name__ == "__main__":
    import os
    # Ensure AWS credentials and region are set in environment variables for a runnable example
    # e.g., export AWS_ACCESS_KEY_ID='YOUR_KEY' AWS_SECRET_ACCESS_KEY='YOUR_SECRET' AWS_REGION='us-east-1'
    if not all(os.environ.get(k) for k in ['AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY', 'AWS_REGION']):
        print("Please set AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_REGION environment variables.")
    else:
        try:
            buckets = list_s3_bucket_names()
            if buckets:
                print(f"Found buckets: {', '.join(buckets)}")
            else:
                print("No S3 buckets found.")
        except Exception as e:
            print(f"An error occurred: {e}")

view raw JSON →