Type annotations for boto3 STS
mypy-boto3-sts provides PEP 561-compliant type annotations for the `boto3` STS (AWS Security Token Service) client, compatible with mypy, pyright, VSCode, PyCharm, and other type-checking tools. It ensures type safety and offers enhanced code completion for `boto3.client("sts")` operations. The current version, 1.42.3, aligns with boto3 1.42.3 and is generated by mypy-boto3-builder 8.12.0. The library follows the release cadence of `boto3` and its builder.
Warnings
- breaking Starting with `mypy-boto3-builder` 8.12.0 (which generates this package), support for Python 3.8 has been removed. Users on Python 3.8 should update their Python version.
- breaking TypedDict names for 'packed' method arguments may have changed, becoming shorter (e.g., `CreateDistributionRequestRequestTypeDef` became `CreateDistributionRequestTypeDef`). This was part of `mypy-boto3-builder` 8.9.0.
- gotcha For optimal IDE support (especially VSCode) and `mypy` accuracy, it is recommended to explicitly annotate `boto3.client()` calls with the `STSClient` type, even though auto-discovery works for basic cases in tools like PyCharm.
- gotcha When using `mypy-boto3-sts` with Pylint, you might encounter 'undefined variable' warnings if the type stubs are not installed in the production environment. A common workaround is to use `if TYPE_CHECKING:` blocks.
Install
-
pip install mypy-boto3-sts boto3
Imports
- STSClient
from mypy_boto3_sts.client import STSClient
- AssumeRoleResponseTypeDef
from mypy_boto3_sts.type_defs import AssumeRoleResponseTypeDef
Quickstart
import boto3
from mypy_boto3_sts.client import STSClient
from mypy_boto3_sts.type_defs import AssumeRoleResponseTypeDef
from os import environ
# Instantiate a boto3 session and an STS client, with explicit type hinting.
# In a real scenario, boto3 would pick up credentials from environment variables,
# shared credential files, or IAM roles.
session = boto3.Session()
client: STSClient = session.client("sts")
try:
# Example: Assume a role with type-hinted arguments and response.
# Replace 'YOUR_ROLE_ARN' with an actual AWS IAM Role ARN for testing.
role_arn = environ.get("AWS_STS_ROLE_ARN", "arn:aws:iam::123456789012:role/MyTestRole")
response: AssumeRoleResponseTypeDef = client.assume_role(
RoleArn=role_arn,
RoleSessionName="MySessionName",
DurationSeconds=900 # Minimum duration is 900 seconds (15 minutes)
)
print("Successfully assumed role.")
print(f"Assumed Role User ARN: {response['AssumedRoleUser']['Arn']}")
print(f"Credentials Expiration: {response['Credentials']['Expiration']}")
except client.exceptions.ClientError as e:
print(f"AWS Client Error: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")