小编Jan*_*cki的帖子

Mypy错误 - 分配中不兼容的类型

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

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

    if condition:
        result["success"] = True
        return result
    else:
        result["message"] = "error message"
    return result
Run Code Online (Sandbox Code Playgroud)

当我运行Mypy(版本0.52)时,我收到此错误:

error: Incompatible types in assignment (expression has type "str", target has type "bool")
Run Code Online (Sandbox Code Playgroud)

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

python mypy

5
推荐指数
1
解决办法
5226
查看次数

mypy错误 - 尽管使用'Union'不兼容类型

请考虑以下代码示例:

from typing import Dict, Union

def count_chars(string) -> Dict[str, Union[str, bool, int]]:
    result = {}  # type: Dict[str, Union[str, bool, int]]

    if isinstance(string, str) is False:
        result["success"] = False
        result["message"] = "Inavlid argument"
    else:
        result["success"] = True
        result["result"] = len(string)
    return result

def get_square(integer: int) -> int:
    return integer * integer

def validate_str(string: str) -> bool:
    check_count = count_chars(string)
    if check_count["success"] is False:
        print(check_count["message"])
        return False
    str_len_square = get_square(check_count["result"])
    return bool(str_len_square > 42)

result = validate_str("Lorem ipsum")
Run Code Online (Sandbox Code Playgroud)

在针对此代码运行mypy时,将返回以下错误:

error: …
Run Code Online (Sandbox Code Playgroud)

python types typing typechecking mypy

4
推荐指数
1
解决办法
1000
查看次数

标签 统计

mypy ×2

python ×2

typechecking ×1

types ×1

typing ×1