python - 如何让 mypy 识别更新版本的 python?
问题描述
我刚刚将我的项目更新到 Python 3.7,当我在项目上运行 mypy 时看到了这个错误:error: "Type[datetime]" has no attribute "fromisoformat"
datetime
在 Python 3.7 中确实有一个函数fromisoformat
,但在以前的 Python 版本中没有。为什么 mypy 会报告这个错误,我怎样才能让它正确分析 Python 3.7?
到目前为止我尝试过的事情:
- 删除 .mypy_cache(其中有一个名为 的可疑子文件夹
3.6
) - 重新安装 mypy
pip install --upgrade --force-reinstall mypy
重现:
创建一个 python 3.6 项目
在项目venv中安装mypy 0.761(最新)
使用 mypy (
mypy .
)扫描项目将项目更新为 python 3.7
添加一个包含此代码的文件:
from datetime import datetime datetime.fromisoformat('2011-11-04 00:05:23.283')
再次扫描项目(
mypy .
)[更新:这实际上工作正常。它正在重新运行我的 precommit 钩子,而没有在导致问题的新 Python 版本 venv 上重新安装 precommit。]
解决方案
解决方案很简单:只需使用 --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 版本)
推荐阅读
- c++ - 在 C++ 类中初始化 C 数组
- sql - 即使有数据查询也不给出输出
- java - 如何将 XML 转换为具有二进制数据内容的 Json
- javascript - 页面转换时清除 redux 状态
- javascript - 滚动侦听器中风dashoffset在像素范围之间绘制SVG?
- elasticsearch - 大写字母在弹性搜索中应该排在第一位
- python - 每次我运行我的代码时,只有几个按钮被点击,然后我被一个 Element Click Intercepted Exception - Selenium Python 击中
- python - 我在尝试制作简单的纸牌游戏时遇到了问题
- three.js - GLTF 和分层 - 层上移动的对象被剪切/隐藏
- javascript - Select2 字段 .value 属性不会在 .onchange 函数内更改