以下文件:
from typing import List
class A:
def __init__(self, myStr):
self.chars: List[int] = list(myStr)
def toString(self):
return "".join(self.chars)类型检查(注意字符应该是Liststr而不是Listint):➜ 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是Listint,join接受Iterablestr)
发布于 2020-06-09 04:54:19
mypy的这种行为是设计出来的。Mypy假设,如果函数签名缺少类型提示,则用户不希望对该函数进行类型检查,因此跳过对该函数体的分析。
此行为旨在使在处理大型代码库时逐步添加类型提示变得更容易:您最终只会收到关于您有机会检查和迁移的函数的警告,而不是前面的警告墙。
如果您不喜欢这种行为,并且希望mypy不管怎样都尝试类型检查函数体,那么可以传入--check-untyped-defs命令行标志(或config file option)。
或者,如果您想让mypy在忘记添加类型签名时发出警告,可以使用--disallow-untyped-defs and --disallow-incomplete-defs标志。
除了其他标志之外,--strict标志还可以启用所有这三个标志。您可以运行mypy --help来自己仔细检查这一点。
https://stackoverflow.com/questions/62265366
复制相似问题