如何避免在nvim中通过mason安装mypy时出现“无法找到实现或库存根”的问题

huangapple go评论66阅读模式
英文:

How to avoid "cannot find implementation or library stub" when mypy is installed via mason in nvim

问题

我正在使用Neovim,并使用mason安装了mypy,还使用null-nvim进行了配置:

local sources = { null_ls.builtins.diagnostics.mypy }

这里,通过mason安装的mypy实际上安装在~/.local/share/nvim/mason/packages/mypy目录下的一个独立虚拟环境中。如果第三方库安装在另一个环境中,似乎mypy会始终引发“无法找到实现或库存根”的警告。

例如,我激活了myenv,在其中安装了openai,然后我使用Neovim打开了一个Python文件:

如何避免在nvim中通过mason安装mypy时出现“无法找到实现或库存根”的问题

另一方面,如果我在myenv内部安装了mypy,那么一切都能正常工作。但这种方法要求我为每个虚拟环境都安装一份mypy的拷贝。如何在通过mason安装时避免警告消息?


更新

> 例如,如果您正在虚拟环境中运行代码,请确保在虚拟环境内安装并使用mypy。或者,如果您想使用全局安装的mypy,请将--python-executable命令行标志设置为指向包含已安装的第三方包的Python解释器。

似乎mypy无法检测到我正在使用的当前虚拟环境。

英文:

I am using Neovim and installed mypy with mason, and I also configured it using null-nvim:

local sources = { null_ls.builtins.diagnostics.mypy }

Here, mypy, installed by mason, in fact, is installed in a separate virtual environment under ~/.local/share/nvim/mason/packages/mypy. It seems that mypy will always raise warnings "cannot find implementation or library stub" if the third-party library is installed in another environment.

For example, I activated myenv where openai is installed, and then I opened a Python file using Neovim:

如何避免在nvim中通过mason安装mypy时出现“无法找到实现或库存根”的问题

On the other hand, if I installed mypy inside myenv, then everything works well. But this method requires me to install every copy of mypy for every virtual environment. How to avoid the warning message when I installed it via mason?


Update

> For example, if you are running your code in a virtualenv, make sure to install and use mypy within the virtualenv. Alternatively, if you want to use a globally installed mypy, set the --python-executable command line flag to point the Python interpreter containing your installed third party packages.

It seems that mypy is not able to detect the current virutalenv I am using.

答案1

得分: 2

以下是在Linux和macOS中的解决方法:

nls.builtins.diagnostics.mypy.with({
    extra_args = function()
        local virtual = os.getenv("VIRTUAL_ENV") or os.getenv("CONDA_DEFAULT_ENV") or "/usr"
        return { "--python-executable", virtual .. "/bin/python3" }
    end,
}),

上面的代码首先检测virtualenv,否则将使用默认的/usr/bin/python3作为--python-executable

英文:

Here is a workaround way in both Linux and macOS:

nls.builtins.diagnostics.mypy.with({
    extra_args = function()
    local virtual = os.getenv("VIRTUAL_ENV") or os.getenv("CONDA_DEFAULT_ENV") or "/usr"
    return { "--python-executable", virtual .. "/bin/python3" }
    end,
}),

The code above detects virutalenv first, and otherwise, it will use default /usr/bin/python3 as the --python-executable.

huangapple
  • 本文由 发表于 2023年6月16日 13:20:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76487150.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定