mypy-boto3-ce: Type Annotations for AWS Cost Explorer
mypy-boto3-ce provides comprehensive type annotations for the AWS Boto3 Cost Explorer (CE) service, ensuring static type checking for your Python code. It is automatically generated by `mypy-boto3-builder` (currently version 8.12.0) and is updated frequently to align with `boto3` and `botocore` releases, enhancing code quality and developer experience by catching potential AWS-related errors before runtime.
Warnings
- breaking Support for Python 3.8 was officially removed with `mypy-boto3-builder` version 8.12.0. Ensure your project runs on Python 3.9 or higher.
- breaking TypeDef naming conventions were changed in `mypy-boto3-builder` 8.9.0. This could affect existing type hints for method arguments (e.g., `CreateDistributionRequestRequestTypeDef` became `CreateDistributionRequestTypeDef`) and conflicting TypeDef postfixes (e.g., `CreateDistributionExtraRequestTypeDef` to `CreateDistributionRequestExtraTypeDef`).
- gotcha Explicit type annotations are highly recommended for `boto3.client`, `boto3.session.client`, `client.get_waiter`, and `client.get_paginator` calls. While some IDEs (like PyCharm) and static analyzers (like Mypy) might infer types, VSCode's Python extension might not fully support function overloads, leading to a lack of auto-completion and type checking without explicit hints.
- gotcha To avoid a runtime dependency on `mypy-boto3-ce` in production environments, it is common practice to guard imports with `if TYPE_CHECKING:` from the `typing` module.
- deprecated The `mypy-boto3-builder` project occasionally removes or renames service stubs (e.g., `sms-voice` was removed in 8.11.0 and replaced by `pinpoint-sms-voice`). While `mypy-boto3-ce` is stable, be aware that services may change, requiring updates to your stub installations.
Install
-
pip install mypy-boto3-ce -
pip install 'boto3-stubs[ce]'
Imports
- CostExplorerClient
from mypy_boto3_ce.client import CostExplorerClient
- AnomalyDateIntervalTypeDef
from mypy_boto3_ce.type_defs import AnomalyDateIntervalTypeDef
- AccountScopeType
from mypy_boto3_ce.literals import AccountScopeType
Quickstart
from typing import TYPE_CHECKING
import boto3
import os
if TYPE_CHECKING:
from mypy_boto3_ce.client import CostExplorerClient
from mypy_boto3_ce.type_defs import GetCostAndUsageResponseTypeDef
# It's recommended to use explicit type hints for boto3.client for better IDE support
# and type checking, especially if not using the 'boto3-stubs' full package.
def get_cost_explorer_data(client: "CostExplorerClient") -> "GetCostAndUsageResponseTypeDef":
# Example: Retrieve cost and usage data for the last 7 days
response = client.get_cost_and_usage(
TimePeriod={
'Start': '2023-01-01',
'End': '2023-01-08'
},
Granularity='DAILY',
Metrics=['BlendedCost', 'UnblendedCost'],
# Add other parameters as needed, e.g., Filter, GroupBy
)
return response
if __name__ == '__main__':
# Ensure AWS credentials are configured (e.g., via environment variables or AWS CLI config)
# For this example, we'll create a client. In a real app, you might pass an existing client.
print("Initializing Boto3 Cost Explorer client...")
ce_client: "CostExplorerClient" = boto3.client(
"ce",
region_name=os.environ.get('AWS_REGION', 'us-east-1'),
aws_access_key_id=os.environ.get('AWS_ACCESS_KEY_ID', 'DUMMY_KEY'),
aws_secret_access_key=os.environ.get('AWS_SECRET_ACCESS_KEY', 'DUMMY_SECRET')
)
try:
# The `get_cost_explorer_data` function now benefits from type hints
# for both the client object and the response structure.
costs_data = get_cost_explorer_data(ce_client)
print("Successfully retrieved Cost Explorer data (truncated for brevity):")
# In a real scenario, you'd process costs_data. For this example, just print a key.
if costs_data and 'ResultsByTime' in costs_data:
print(f"First result time period: {costs_data['ResultsByTime'][0]['TimePeriod']}")
else:
print("No results or unexpected response structure.")
except Exception as e:
print(f"An error occurred: {e}")