請考慮下面的代碼示例: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專家邁克爾,非常感謝! –