在返回boto3对象的函数中添加类型提示?

Yar*_*tov 6 amazon-web-services python-3.x boto3

如何在返回各种boto3资源的函数中添加类型提示?我想在像PyCharm这样的IDE中自动完成/检查返回值。Boto3做一些工厂创建魔术,所以我不知道如何正确声明类型

import boto3 ec2 = boto3.Session().resource('ec2') a = ec2.Image('asdf') a.__class__ # => boto3.resources.factory.ec2.Image

但是boto3.resources.factory.ec2.Image似乎不是Python可以识别的类。因此,我不能将其用作类型提示。

文档显示,返回类型为EC2.Image。但是有没有办法将该类型导入为常规Python类型呢?

All*_*ter 12

2021 年更新

正如@eega 提到的,我不再维护这个包。我建议检查一下boto3-stubs。这是一个更成熟的版本boto3_type_annotations

原答案

我制作了一个可以帮助解决此问题的软件包,boto3_type_annotations. 它也可以在有或没有文档的情况下使用。下面的示例用法。我的 github 上还有一个 gif,显示它使用 PyCharm 进行操作。

import boto3
from boto3_type_annotations.s3 import Client, ServiceResource
from boto3_type_annotations.s3.waiter import BucketExists
from boto3_type_annotations.s3.paginator import ListObjectsV2

# With type annotations

client: Client = boto3.client('s3')
client.create_bucket(Bucket='foo')  # Not only does your IDE knows the name of this method, 
                                    # it knows the type of the `Bucket` argument too!
                                    # It also, knows that `Bucket` is required, but `ACL` isn't!

# Waiters and paginators and defined also...

waiter: BucketExists = client.get_waiter('bucket_exists')
waiter.wait('foo')

paginator: ListObjectsV2 = client.get_paginator('list_objects_v2')
response = paginator.paginate(Bucket='foo')

# Along with service resources.

resource: ServiceResource = boto3.resource('s3')
bucket = resource.Bucket('bar')
bucket.create()

# With type comments

client = boto3.client('s3')  # type: Client
response = client.get_object(Bucket='foo', Key='bar')


# In docstrings

class Foo:
    def __init__(self, client):
        """
        :param client: It's an S3 Client and the IDE is gonna know what it is!
        :type client: Client
        """
        self.client = client

    def bar(self):
        """
        :rtype: Client
        """
        self.client.delete_object(Bucket='foo', Key='bar')
        return self.client
Run Code Online (Sandbox Code Playgroud)


eeg*_*ega 7

Allie Fitter 提到的boto3_type_annotations已弃用,但她链接到替代方案:https : //pypi.org/project/boto3-stubs/

  • 呵呵。很好看。37年过去了,我已经习惯被误认为是女人了。 (4认同)
  • 根据他的简历,艾莉是一个“花花公子”。;) (2认同)