Type Annotations for Boto3 EC2
types-boto3-ec2 provides comprehensive type annotations for the Amazon EC2 service client in boto3, enabling static type checking with tools like mypy, pyright, and enhanced IDE support. It is part of the mypy-boto3-builder ecosystem, which generates separate stub packages for each AWS service. The current version is 1.42.85, with frequent updates synchronized with boto3 releases.
Warnings
- breaking Support for Python 3.8 was removed in mypy-boto3-builder 8.12.0 (and consequently for types-boto3-ec2 versions generated by it). Python 3.9+ is now required.
- gotcha This is a service-specific stub package. To get type annotations for other AWS services (e.g., S3, Lambda), you must install their respective `types-boto3-<service>` packages (e.g., `types-boto3-s3`). Installing just `types-boto3` will install a 'full' package but it's often more efficient to install specific stubs.
- breaking In mypy-boto3-builder 8.9.0, there were breaking changes to TypeDef naming conventions, where packed method arguments used shorter names (e.g., `CreateDistributionRequestRequestTypeDef` became `CreateDistributionRequestTypeDef`) and conflicting `Extra` postfixes moved to the end (e.g., `CreateDistributionExtraRequestTypeDef` became `CreateDistributionRequestExtraTypeDef`).
- gotcha The `mypy-boto3` ecosystem switched to PEP 561 compliant packages in version 8.12.0. This primarily affects how type checkers locate and interpret the installed stub files.
- gotcha Pylint might complain about undefined variables when using type hints with `types-boto3-ec2` outside of a `TYPE_CHECKING` block. It is recommended to use an `if TYPE_CHECKING:` guard and set types to `object` in the `else` branch to avoid runtime dependencies and Pylint warnings.
Install
-
pip install types-boto3-ec2 -
pip install 'boto3-stubs[ec2]'
Imports
- EC2Client
from types_boto3_ec2 import EC2Client
- EC2ServiceResource
from types_boto3_ec2 import EC2ServiceResource
Quickstart
import boto3
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from types_boto3_ec2 import EC2Client
# Boto3 client will be automatically typed by mypy-boto3-ec2 if installed
ec2_client: EC2Client = boto3.client('ec2')
# Example usage with type-hinted client
response = ec2_client.describe_instances(
Filters=[
{
'Name': 'instance-state-name',
'Values': ['running']
},
]
)
for reservation in response['Reservations']:
for instance in reservation['Instances']:
print(f"Instance ID: {instance['InstanceId']}, Type: {instance['InstanceType']}")