python-3.x 在返回boto3对象的函数中添加类型提示?

wdebmtf2  于 2023-03-31  发布在  Python
关注(0)|答案(3)|浏览(144)

如何在返回各种boto 3资源的函数中添加类型提示?我想在PyCharm等IDE中获得自动完成/检查返回值。Boto 3做了一些工厂创建魔术,所以我不知道如何正确声明类型
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类型导入?

hc8w905p

hc8w905p1#

更新2021

正如@eega所提到的,我不再维护这个软件包了。我建议你看看boto3-stubs。它是boto3_type_annotations的一个更成熟的版本。

原始答案

我做了一个可以帮助解决这个问题的软件包,boto3_type_annotations。它可以带文档也可以不带文档。下面是示例用法。在我的github上还有一个使用PyCharm的GIF。

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
pxyaymoc

pxyaymoc2#

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

uz75evzq

uz75evzq3#

看看aws-samples中的这个项目,它是一个带有boto_stubs的瘦集成层,并且它具有开箱即用的显式类型提示https://github.com/aws-samples/boto-session-manager-project/tree/main

相关问题