如何在返回各种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可以识别的类。所以我不能将其用作类型提示。
docs显示返回类型为EC2.Image
。但是有没有办法将该类型导入为常规Python类型?
答案 0 :(得分:2)
已弃用Allie Fitter提到的boto3_type_annotations,但她链接到另一个选择:https://pypi.org/project/boto3-stubs/
答案 1 :(得分:0)
我制作了一个可以帮助您解决问题的软件包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