mypy是否只有在函数声明返回类型时才进行类型检查?

问题描述 投票:0回答:1

以下文件。

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])

python python-3.x typechecking mypy
1个回答
1
投票

mypy的这种行为是设计出来的。Mypy假设如果一个函数签名缺少类型提示,那么用户还不希望该函数进行类型检查,所以跳过分析该函数体。

这种行为的目的是为了在处理大型代码库时,逐步增加类型提示,使工作变得更容易:你最终只对你有机会检查和迁移的函数发出警告,而不是在前面被一堵警告墙击中。

如果你不喜欢这样的行为,希望mypy无论如何都能尝试检查函数体的类型,可以传入 --check-untyped-defs 命令行标志 配置文件选项).

或者,如果你想让mypy在你忘记添加类型签名时发出警告,使用 --disallow-untyped-defs--disallow-incomplete-defs 旗帜。

旗帜。--strict 标志也可以启用所有这三个标志,还有其他标志。您可以运行 mypy --help 以便自己仔细检查。

© www.soinside.com 2019 - 2024. All rights reserved.