How do I add type hints to fuctions with boto3 objects in python?

Viewed 1903

How do I add type hints to functions using boto3 without using external libraries like mypy_boto3? This is especially confusing with the boto3.client which returns the object of the type botocore.client.s3 which is unavailable to import.

Example functions to annotate in script below would be get_client and list_objects:

import boto3


def get_client():
    return boto3.client('s3')


def list_objects(client):
    response = client.list_objects(Bucket="a", Prefix="b")
    for content in response.get('Contents', []):
        yield content.get('Key')


client = get_client()
for f in list_objects(client):
    print(f)

I am getting started in typing module and had a look at different options available in python 3.6+ , but am unclear on what would be the type hints for runtime types like the object returned by boto3.client in this case.

2 Answers

Per PEP 484 you need to use Forward references if you're not interested in the external libraries that are being developed. Just put the type in single quotes.

    def get_object(s3_client: 'botocore.client.S3') -> str:
        ...

This question is already answered in this StackOverflow question.

That being said, you can do this:

import boto3
import botocore

def get_client():
   client = boto3.client('s3')
   if not (client and isinstance(client, botocore.client.BaseClient):
       do_some_error_handling_here()
   return client


def list_objects(client: botocore.client.BaseClient):
    response = client.list_objects(Bucket="a", Prefix="b")
    for content in response.get('Contents', []):
        yield content.get('Key')


client = get_client()
for f in list_objects(client):
    print(f)
Related