考虑以下代码示例:
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 错误?