你如何让 mypy 识别更新版本的 python?

How do you get mypy to recognize a newer version of python?

我刚刚将我的项目更新到 Python 3.7,当我在项目上 运行 mypy 时看到这个错误:error: "Type[datetime]" has no attribute "fromisoformat"

datetime 在 Python 3.7 中有函数 fromisoformat,但在 Python 的早期版本中没有。为什么 mypy 报这个错,我怎样才能让它正确分析 Python 3.7?

到目前为止我尝试过的事情:

重现:

解决方案很简单:只需 运行 带有 --python-version 标志的 mypy。所以在我的例子中是 --python-version=3.7

如果您使用 pre-commit,您还可以在 .pre-commit-config.yaml 中将其添加为预提交检查中的参数。我的看起来像这样:

repos:

...

- repo: https://github.com/pre-commit/mirrors-mypy
  rev: v0.750  # Use the sha / tag you want to point at
  hooks:
      - id: mypy
        args: [--python-version=3.7]

如果您 运行 经常从命令行使用 mypy,您也可以按照此处所述将其添加到配置文件中https://mypy.readthedocs.io/en/stable/config_file.html

另一个注意事项:如果 mypy 在您的预提交挂钩 运行 时报告错误,而不是当它本身来自项目 venv 运行 时,那么您需要

  • 添加 python-version 作为参数,就像我在上面所做的那样,或者
  • 在新项目 venv 中重新安装预提交(使用正确的 python 版本)

您 运行 在 Python 的旧版本下使用 mypy。 mypy 默认为用于 运行 的 Python 版本。

您有两个选择:

  • 您可以使用 --python-version command-line option:

    更改 Python 语言版本

    This flag will make mypy type check your code as if it were run under Python version X.Y. Without this option, mypy will default to using whatever version of Python is running mypy.

    我会把它放在 project mypy configuration file; the equivalent of the command-line switch is named python_version;把它放在全局 [mypy] 部分:

    [mypy]
    python_version = 3.7
    
  • 将 mypy 安装到项目的 virtualenv 中,以便它使用完全相同的 Python 版本。

请注意,如果您在命令行或 configuration file 中看到此问题(并且没有意外设置 --python-version,您肯定 不是 运行从你的项目 venv 中安装 mypy。