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
正如@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)
Allie Fitter 提到的boto3_type_annotations已弃用,但她链接到替代方案:https : //pypi.org/project/boto3-stubs/
| 归档时间: |
|
| 查看次数: |
724 次 |
| 最近记录: |