繁体   English   中英

Mypy 错误 - 赋值中的类型不兼容

[英]Mypy error - incompatible types in assignment

我的函数看起来像这个简化的代码示例:

def my_func() -> dict:
    result = {"success": False}

    if condition:
        result["success"] = True
        return result
    else:
        result["message"] = "error message"
    return result

当我运行 Mypy(0.52 版)时,出现此错误:

error: Incompatible types in assignment (expression has type "str", target has type "bool")

并且错误指向我的代码示例中的倒数第二行。 为什么 mypy 返回此错误? 我的代码无效(以任何方式)还是这是一些 mypy 错误?

问题是 mypy 推断result变量的类型是Dict[str, bool]由于您在第 2 行首次初始化它的方式。

因此,当您稍后尝试插入 str 时,mypy(理所当然地)会抱怨。 您有多种修复代码的选项,我将按照类型安全从低到高的顺序列出。

选项 1 是声明您的字典,使其值属于Any类型——也就是说,您的值根本不会进行类型检查:

from typing import Any, Dict

def my_func(condition: bool) -> Dict[str, Any]:
    result = {"success": False}  # type: Dict[str, Any]

    if condition:
        result["success"] = True
    else:
        result["message"] = "error message"
    return result

请注意,我们需要注释您的第二行,以便为 mypy 提供有关result类型应该是什么的提示,以帮助其推理过程。

如果您使用的是 Python 3.6+,则可以使用以下替代语法对该行进行注释,该语法使用变量注释(从 Python 3.6 开始是新的):

result: Dict[str, Any] = {"success": False}

选项 2 的类型安全性更高——使用Union将您的值声明为 strs 或 bools,但别无其他。 这不是完全类型安全的,但至少您仍然可以对 dict 进行一些检查。

from typing import Any, Dict

def my_func(condition: bool) -> Dict[str, Union[str, bool]]:
    result = {"success": False}  # type: Dict[str, Union[str, bool]]

    if condition:
        result["success"] = True
    else:
        result["message"] = "error message"
    return result

您可能会发现该类型注释有点长/输入起来很烦人,因此您可以使用类型别名来提高可读性(并且可以选择使用变量注释语法),如下所示:

ResultJson = Dict[str, Union[str, bool]]

def my_func(condition: bool) -> ResultJson
    result: ResultJson = {"success": False}
    # ...snip...

选项 3 是最类型安全的,尽管它确实需要您使用实验性的“TypedDict”类型,它允许您将特定类型分配给字典中的不同字段。 也就是说,使用这种类型的风险由您自己承担——AFAIK 它还没有被添加到 PEP 484 中,这意味着其他类型检查工具(如 Pycharm 的检查器)没有义务理解这一点。 Mypy 本身最近才添加了对 TypedDict 的支持,因此可能仍然有问题:

from typing import Optional
from mypy_extensions import TypedDict

ResultJson = TypedDict('ReturnJson', {'success': bool, 'message': Optional[str]})

def my_func(condition: bool) -> ResultJson:
    result = {"success": False, "message": None}  # type: ResultJson

    if condition:
        result["success"] = True
    else:
        result["message"] = "error message"
    return result

如果要使用此选项,请务必安装mypy_extensions包。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM