Edw*_*emo 1 python typechecking python-3.x mypy
以下文件:
from typing import List
class A:
def __init__(self, myStr):
self.chars: List[int] = list(myStr)
def toString(self):
return "".join(self.chars)
Run Code Online (Sandbox Code Playgroud)
typechecks (注意字符应该是 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)
Run Code Online (Sandbox Code Playgroud)
在这种情况下,有人可以解释 mypy 的行为吗?为什么需要在函数中添加返回类型来强制mypy正确诊断问题?(它已经有了所有必要的信息:那个字符是 List[int] 并且 join 接受 Iterable[str])
mypy 的这种行为是设计使然。Mypy 假设如果函数签名缺少类型提示,则用户不希望对该函数进行类型检查,因此跳过分析该函数体。
此行为旨在在处理大型代码库时更轻松地逐步添加类型提示:您最终只会收到有关您有机会检查和迁移的函数的警告,而不是预先收到警告墙。
如果您不喜欢这种行为并且希望 mypy 无论如何都尝试类型检查函数体,请传入--check-untyped-defs命令行标志(或配置文件选项)。
或者,如果您希望 mypy 在您忘记添加类型签名时发出警告,请使用--disallow-untyped-defs和--disallow-incomplete-defs标志。
该--strict标志还可以启用所有这三个标志等。你可以mypy --help自己跑去仔细检查一下。
| 归档时间: |
|
| 查看次数: |
356 次 |
| 最近记录: |