mypy-boto3-ec2 Type Stubs
mypy-boto3-ec2 provides type annotations for the boto3 EC2 service. It ensures that your boto3 client calls for EC2 are type-checked by tools like MyPy, catching potential errors at development time. The current version is 1.42.85, closely following boto3/botocore releases, with frequent updates tied to AWS API changes.
Warnings
- breaking Python 3.8 support was removed for all `mypy-boto3-*` packages, including `mypy-boto3-ec2`, starting from version `8.12.0` of the builder. Projects on Python 3.8 will need to upgrade their Python version to 3.9+.
- gotcha It's crucial to install `mypy-boto3-ec2` (or any `mypy-boto3-*` package) with a version that matches your `boto3` installation as closely as possible. Mismatched versions can lead to incorrect type hints or `mypy` errors.
- breaking From builder version `8.9.0`, TypeDef names for packed method arguments were shortened (e.g., `CreateDistributionRequestRequestTypeDef` became `CreateDistributionRequestTypeDef`). Additionally, conflicting TypeDef `Extra` postfixes were moved (e.g., `CreateDistributionExtraRequestTypeDef` became `CreateDistributionRequestExtraTypeDef`).
- gotcha AWS service names can change or be deprecated (e.g., `sms-voice` was replaced by `pinpoint-sms-voice` for `mypy-boto3-*` packages in builder version `8.11.0`). While `ec2` is stable, be aware that you might need to update the specific `mypy-boto3-*` package if you work with other AWS services whose names evolve.
Install
-
pip install mypy-boto3-ec2 -
pip install boto3 mypy
Imports
- EC2Client
from mypy_boto3_ec2.client import EC2Client
- EC2ServiceResource
from mypy_boto3_ec2.service_resource import EC2ServiceResource
- DescribeInstancesResultTypeDef
from mypy_boto3_ec2.type_defs import DescribeInstancesResultTypeDef
Quickstart
import boto3
from mypy_boto3_ec2.client import EC2Client
from mypy_boto3_ec2.type_defs import InstanceTypeDef, ReservationTypeDef
def list_ec2_instances() -> None:
# Type-hint the boto3 client for EC2
ec2_client: EC2Client = boto3.client('ec2')
print('Describing EC2 instances...')
response = ec2_client.describe_instances()
# Use type definitions for better type checking on the response
for reservation in response.get('Reservations', []):
reservation_typed: ReservationTypeDef = reservation
for instance in reservation_typed.get('Instances', []):
instance_typed: InstanceTypeDef = instance
instance_id = instance_typed.get('InstanceId', 'N/A')
instance_type = instance_typed.get('InstanceType', 'N/A')
state = instance_typed.get('State', {}).get('Name', 'N/A')
print(f' Instance ID: {instance_id}, Type: {instance_type}, State: {state}')
if __name__ == '__main__':
# This quickstart assumes AWS credentials are configured (e.g., via environment variables or ~/.aws/credentials)
list_ec2_instances()