繁体   English   中英

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

[英]Adding type-hinting to functions that return boto3 objects?

如何向返回各种 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 类型?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM