Mypy 不捕获类型不匹配

Mypy doesn't catch type mysmatch

mypy==0.720

我的档案:

import yaml


def read_secret_yaml() -> str: # Real return type is dict.
    """
    Read secret.yaml (not added to Git).
    """
    current_dir = os.path.dirname(os.path.realpath(__file__))
    path = os.path.join(current_dir, "../../doc/secret.yaml")
    stream = open(path, "r")
    secret = yaml.load(stream, Loader=yaml.FullLoader)

    return secret

这个函数returns一个字典。我特意把result tytpe改成str来检查mypy是否抓到这个类型mysmatch。

命令是:

mypy --strict-optional general_lib.py

我没有收到错误消息。

你能告诉我这是 mypy 的正确行为还是我做错了什么。

如评论中所述,yaml.load 将 return 类型为 Any 的值。这是故意的:一个 YAML 文件可以包含任意数量的东西(一个字典,一个列表......),所以类型检查器将无法推断出你的 secret 变量到底是什么.

换句话说,在这种情况下,您的数据是合法的动态数据,这意味着您确实没有什么好的静态类型可以使用。


如果你想让 mypy 在你尝试 return 从一个没有 的函数中输入 Any 类型的东西时发出警告,它将return Any,使用--warn-return-any标志。这会导致 mypy 报告 Returning Any from function declared to return "str" 错误。

如果您想对此更加严格,也可以探索使用 disallow dynamic typing mypy 标志系列。