Finalización de código y verificación de tipo para boto3

imagen


Imagen cortesía de anotaciones de tipo boto3, Allie Fitter


En este momento, pocas personas escriben grandes proyectos de Python sin anotaciones de tipo. Es simple y le permite detectar un montón de errores incluso en la etapa de escribir código, y funciona de manera muy inteligente. Pero vale la pena agregar boto3 a la dependencia , y mypy comienza a estar lleno de mensajes que las anotaciones de tipo boto3no existen en la naturaleza.


, 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-. ?


Dado que boto3muchos métodos y clases en el mismo archivo se llaman iguales, para el correcto funcionamiento de las anotaciones, el módulo se importa a sí mismo. Esto no funciona en Python 3.6.5 y no se ve muy bien. Cuales son las alternativas?


Y, por último, si todo está bien con C #, puede agregar soporte literal a funciones sobrecargadas para Python Language Server para que todo funcione de manera inmediata en VSCode. No pude y me di por vencido.


¡Gracias a todos!

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


All Articles