Boto3的代码完成和类型检查

图片


图片由boto3类型注释提供,Allie Fitter


目前,很少有人编写没有类型注释的大型Python项目。它很简单,即使在编写代码的阶段,您也可以捕获很多错误,并且运行非常聪明。但是值得将boto3添加到依赖项中,并且mypy开始充满了boto3本质上不存在类型注释的消息


, boto3 botostubs. , mypy .


boto3-type-annotations, , mypy .


boto3, ?


mypy


, boto3 1.11.9 EC2, DynamoDB S3. Python 3.6.9 . , , boto3-stubs 1.11.9.x .


#   boto3 ,     
pip install boto3-stubs[s3,ec2,dynamodb]==1.11.9.0

#     pip, pipfile  poetry,
#    whl-,     
#   
python -m mypy_boto3

… ! mypy , , , boto3, .


- !


, .


VSCode , . boto3.client, boto3_session.client,boto3.resource, boto3_session.resource, client.get_waiter client.get_paginator.


PyCharm - , 15 , .


import boto3

from mypy_boto3 import dynamodb

#   ,    
client: dynamodb.DynamoDBClient = boto3.client("dynamodb")

# IDE        
client.query("my_table")


import boto3

from mypy_boto3 import s3

# PyCharm  mypy      ,   
client: s3.S3Client = boto3.client("s3")

# IDE   ,  ,  --
client.create_bucket(Bucket="bucket")

# ,   mypy     

# (mypy) error: Missing positional argument "Key" in call to "get_object" of "S3Client"
client.get_object(Bucket="bucket")

# (mypy) error: Argument "Key" to "get_object" of "S3Client" has incompatible type "None"; expected "str"
client.get_object(Bucket="bucket", Key=None)

resource: s3.S3ServiceResource = boto3.Session(region_name="us-west-1").resource("s3")

#   -     
bucket = resource.Bucket("bucket")

# (mypy) error: Unexpected keyword argument "key" for "upload_file" of "Bucket"; did you mean "Key"?
bucket.upload_file(Filename="my.txt", key="my-txt")

# waiter'   paginator'  
#         
waiter: s3.BucketExistsWaiter = client.get_waiter("bucket_exists")
paginator: s3.ListMultipartUploadsPaginator = client.get_paginator(
    "list_multipart_uploads"
)


mypy-boto3-builder - boto3. boto3, .


json- botocore , boto3 .



, , .


post-install , whl-. ?


由于boto3同一个文件中的许多方法和类都称为相同的,因此为了正确执行批注,模块将自行导入。这在Python 3.6.5中不起作用,看起来也不是很好。有哪些选择?


最后,如果C#一切正常,您可以为Python Language Server的重载函数添加文字支持,以便所有内容也可以在VSCode中使用。我不能,放弃了。


谢谢大家!

Source: https://habr.com/ru/post/undefined/


All Articles