请考虑下面的代码示例:mypy错误 - 不兼容的类型,尽管使用“联盟”
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")
当运行mypy对这个代码,返回以下错误:
error: Argument 1 to "get_square" has incompatible type "Union[str, bool, int]"; expected "int"
,我不知道如何在不使用Dict[str, Any]
作为第一个函数的返回类型或安装'TypedDict'mypy扩展名时避免此错误。是mypy实际上'正确',任何我的代码是不是类型安全的,或者这应该被视为mypy错误?
你是一个真正的mypy专家迈克尔,非常感谢! –