boto3 icon indicating copy to clipboard operation
boto3 copied to clipboard

[Feature Request] Type hints

Open stealthycoin opened this issue 7 years ago • 4 comments
trafficstars

Now that pep 561 has passed its possible to have a typehint package added for boto3.

stealthycoin avatar Oct 04 '18 23:10 stealthycoin

Wouldn't this require an explicit cast though for clients/resources? While we can generate types for the clients/resources, there's not way to automatically associate the creation of a client to a specific type.

boto3.client('s3') -> S3ClientType
boto3.client('ec2') -> EC2ClientType

def client(service_name: str) -> What do we put here?

Though I suppose an explicit cast() is still better than nothing.

jamesls avatar Oct 09 '18 19:10 jamesls

What about type-hints for Resources, Buckets, this would be super useful.

salimfadhley avatar Dec 10 '18 15:12 salimfadhley

Any plans to implement this ?

lqueryvg avatar May 11 '21 22:05 lqueryvg

Linking related feature requests: https://github.com/boto/boto3/issues/1055 and https://github.com/boto/boto3/issues/2036

tim-finnigan avatar Apr 06 '22 19:04 tim-finnigan

Wouldn't this require an explicit cast though for clients/resources? While we can generate types for the clients/resources, there's not way to automatically associate the creation of a client to a specific type.

boto3.client('s3') -> S3ClientType
boto3.client('ec2') -> EC2ClientType

def client(service_name: str) -> What do we put here?

Though I suppose an explicit cast() is still better than nothing.

If I understand your question, it can be addressed with PEP-586 which was accepted in Python 3.8. You can define any number of overloads:

from typing import Literal, Union, overload

@overload
def client(service_name: Literal["s3"]) -> S3ClientType: ...

@overload
def client(service_name: Literal["ec2"]) -> EC2ClientType: ...

def client(service_name: Literal["s3", "ec2"]) -> Union[S3ClientType, EC2ClientType]:
    if service_name == "s3":
        return S3ClientType(...)

    return E2ClientType(...)

Note, at the call site, you must narrow the argument to one of the ones listed in the overloads.

c = client("s3") # fine, c is assigned the type S3ClientType

x = os.getenv("SERVICE_NAME") or "s3"
c = client(x) # Argument of type 'str' cannot be assigned to parameter service_name of type Literal[...

if x == "s3":
    c = client(x) # ok, type narrowing satisfies the type checker

kyle-query avatar Oct 16 '22 23:10 kyle-query

Closing in favor of https://github.com/boto/boto3/issues/1055 for further tracking (provided update here).

tim-finnigan avatar Jan 12 '23 18:01 tim-finnigan