以下文件。
from typing import List
class A:
def __init__(self, myStr):
self.chars: List[int] = list(myStr)
def toString(self):
return "".join(self.chars)
typechecks (注意chars应该是List[str]而不是List[int]): ➜ Python python3 -m mypy temp.py => Success: no issues found in 1 source file
但下面这个文件中,我声明了返回类型toString,却声明了。
from typing import List
class A:
def __init__(self, myStr):
self.chars: List[int] = list(myStr)
def toString(self) -> str:
return "".join(self.chars)
➜ Python python3 -m mypy temp.py
temp.py:9: error: Argument 1 to "join" of "str" has incompatible type "List[int]"; expected "Iterable[str]"
Found 1 error in 1 file (checked 1 source file)
谁能解释一下mypy在这种情况下的行为?为什么我需要在函数中添加返回类型以迫使mypy正确诊断问题?(它已经有所有必要的信息:chars是List[int],join接受Iterable[str])
mypy的这种行为是设计出来的。Mypy假设如果一个函数签名缺少类型提示,那么用户还不希望该函数进行类型检查,所以跳过分析该函数体。
这种行为的目的是为了在处理大型代码库时,逐步增加类型提示,使工作变得更容易:你最终只对你有机会检查和迁移的函数发出警告,而不是在前面被一堵警告墙击中。
如果你不喜欢这样的行为,希望mypy无论如何都能尝试检查函数体的类型,可以传入 --check-untyped-defs
命令行标志 配置文件选项).
或者,如果你想让mypy在你忘记添加类型签名时发出警告,使用 --disallow-untyped-defs
和 --disallow-incomplete-defs
旗帜。
旗帜。--strict
标志也可以启用所有这三个标志,还有其他标志。您可以运行 mypy --help
以便自己仔细检查。