首页 > 解决方案 > 如何让 mypy 识别更新版本的 python?

问题描述

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

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

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

重现:

标签: pythonpython-3.xpython-3.7mypy

解决方案


解决方案很简单:只需使用 --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 中重新安装 pre-commit(使用正确的 python 版本)

推荐阅读