簡體   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