如何解决使用 **kwargs 在 mypy 中看到不兼容的类型
def _describe_assoc(
dxgw_id: str,vpgw_id: str = ""
) -> DescribedirectConnectGatewayAssociationsResultTypeDef:
kwargs = {"directConnectGatewayId": dxgw_id}
if vpgw_id:
kwargs["virtualGatewayId"] = vpgw_id
client: DirectConnectClient = boto3.client("directconnect")
return client.describe_direct_connect_gateway_associations(**kwargs)
当我运行 mypy 时,我得到:
error: Argument 1 to "describe_direct_connect_gateway_associations" of "DirectConnectClient" has
incompatible type "**Dict[str,str]"; expected "Optional[int]"
我在这里看到了一大堆关于此类问题的问题,但在所有情况下,答案都是更改函数定义。在这里,我无法控制函数定义。
如何正确输入所有这些内容以满足 mypy?
解决方法
您在这里遇到的问题是您正在调用的函数 (maxResults
) 的参数之一是 int
。
MyPy 知道您的 kwargs
变量只包含字符串,除此之外它什么都不知道。它知道你的字典正在将 maxResults
映射到一个字符串。
您可以使用 TypedDict
给它一个提示,如下所示:
from typing import TypedDict
class GatewayKwargs(TypedDict,total=False):
directConnectGatewayId: str
virtualGatewayId: str
def _describe_assoc(
dxgw_id: str,vpgw_id: str = ""
) -> DescribeDirectConnectGatewayAssociationsResultTypeDef:
kwargs: GatewayKwargs = {"directConnectGatewayId": dxgw_id}
if vpgw_id:
kwargs["virtualGatewayId"] = vpgw_id
client: DirectConnectClient = boto3.client("directconnect")
return client.describe_direct_connect_gateway_associations(**kwargs)
严格来说,TypedDicts 并不是万无一失的,MyPy 开发人员知道它可以被欺骗接受一些它不应该使用它们的东西。但你真的必须竭尽全力这样做,所以他们会接受这种结构可能是安全的。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。