python - 使用 **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
到一个字符串。
您可以使用 a 给它一个线索,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 开发人员知道它可以被欺骗接受不应该使用它们的东西。但是你真的必须不遗余力地这样做,所以他们会接受这种结构可能是安全的。
推荐阅读
- r - 在 R 中将 JSON 对象列表转换为一个 JSON 对象
- java - 如何删除直方图中的重复字符 [JAVA]
- c# - C# TextBox 只允许在字符串开头使用减号 (-)
- dart - 您如何将列表未来转换为列表以用作变量而不是小部件?
- java - 在 Java 中使用 JComboBox 在 GUI 中进行时间延迟
- c# - 如何使用 if else 从 appsettings.json 中默认提供程序?
- spring-boot - Gradle 不会将 html 文件复制到执行的 jar 中
- javascript - 如何更改传单中特征集合的样式?
- javascript - 在内容框中制作 bs4 导航栏
- java - 到达结尾后从头开始读取 csv 文件(Java、OpenCSV)