boto3
boto3 copied to clipboard
[Feature Request] Type hints
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.
What about type-hints for Resources, Buckets, this would be super useful.
Any plans to implement this ?
Linking related feature requests: https://github.com/boto/boto3/issues/1055 and https://github.com/boto/boto3/issues/2036
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
Closing in favor of https://github.com/boto/boto3/issues/1055 for further tracking (provided update here).