Home > Software design >  What is the correct type annotation for bot3.client(service)
What is the correct type annotation for bot3.client(service)

Time:12-05

With boto3 we can create a client for any service of our choice. For example,

client = boto3.client('s3')

Then if we check the type of the returned object,

print(type(client))
<class 'botocore.client.S3'>

But since there is no botocore.client.S3 (since it is dynamically created), how do we strongly type the client?

The closest I can think of is botocore.client.BaseClient as shown below, which is far from S3 type.

from botocore.client import BaseClient
client: BaseClient = boto3.client('s3')

Any idea?

CodePudding user response:

You could use the botocore.client.S3 class directly as a type hint, even though it doesn't exist at runtime. This works because type hints are only checked at compile time and are not used at runtime:

from botocore.client import S3

client: S3 = boto3.client('s3')

Alternatively, you could create a custom type hint for your S3 client by creating a class that extends BaseClient and use that as the type hint for your client variable:

from botocore.client import BaseClient

class S3Client(BaseClient):
    pass

client: S3Client = boto3.client('s3')

Using the first option, you can ensure that your client variable has the correct type and get the benefits of type checking, without having to create a custom class that extends BaseClient.

CodePudding user response:

Have a look at mypy-boto3:

import boto3
from mypy_boto3_s3 import S3Client
from typing_extensions import reveal_type


def foo(client: S3Client):
    ...


s3_client = boto3.client("s3")

reveal_type(s3_client)  # revealed type is S3Client

foo(s3_client)  # OK!
  • Related