我的函数看起来像这个简化的代码示例:
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?
请考虑以下代码示例:
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)