首页 > 解决方案 > 使用 **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?

标签: pythonmypy

解决方案


您在这里遇到的问题是您正在调用的函数的参数之一 ( 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 开发人员知道它可以被欺骗接受不应该使用它们的东西。但是你真的必须不遗余力地这样做,所以他们会接受这种结构可能是安全的。


推荐阅读