代码之家  ›  专栏  ›  技术社区  ›  Yaroslav Bulatov

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

  •  2
  • Yaroslav Bulatov  · 技术社区  · 6 年前

    如何将类型暗示添加到返回各种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类型导入呢?

    1 回复  |  直到 6 年前
        1
  •  7
  •   Allie Fitter    6 年前

    我做了一个能帮上忙的包裹, 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
    
        2
  •  3
  •   eega    5 年前

    这个 boto3_type_annotations Allie Fitter提到的不推荐使用,但她链接到另一个选项: https://pypi.org/project/boto3-stubs/