You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

nvim中null-ls配置mypy存时诊断仍启动报错问题咨询

解决null-ls中mypy未保存文件打开时触发诊断错误的问题

问题根源

mypy的运行逻辑和black、flake8存在差异:

  • black和flake8支持直接从标准输入(stdin)读取代码内容进行检查/格式化,不需要依赖文件系统中实际存在的文件。
  • mypy默认需要读取文件系统上的物理文件路径来完成类型检查,当你打开一个未保存的新文件时,该路径对应的文件并不存在,即使配置了DIAGNOSTICS_ON_SAVE,null-ls在缓冲区初始化的场景下仍会触发一次检查,导致mypy报错。

解决方案

有两种可行的处理方式:

方式1:让mypy支持从stdin读取内容

修改mypy的配置,强制它从标准输入接收代码,同时传递缓冲区路径作为参数(用于类型上下文),这样即使文件未保存也能正常运行:

null_ls.builtins.diagnostics.mypy.with({
    method = null_ls.methods.DIAGNOSTICS_ON_SAVE,
    args = function(params)
        return {
            "--show-column-numbers",
            "--error-format", "json",
            params.bufname,
            "-", -- 指定从stdin读取内容
        }
    end,
    format = "raw",
    on_output = function(params, done)
        local ok, result = pcall(vim.json.decode, params.output)
        if not ok then
            return done()
        end
        local diagnostics = {}
        for _, err in ipairs(result or {}) do
            table.insert(diagnostics, {
                row = err.line,
                col = err.column,
                end_col = err.end_column,
                message = err.message,
                severity = err.severity == "error" and 1 or 2,
                source = "mypy",
            })
        end
        done(diagnostics)
    end,
})

方式2:仅当文件存在时才运行mypy

通过添加条件判断,跳过不存在的文件检查:

null_ls.builtins.diagnostics.mypy.with({
    method = null_ls.methods.DIAGNOSTICS_ON_SAVE,
    generator_opts = {
        condition = function(params)
            -- 检查文件是否存在,存在才运行诊断
            return vim.fn.filereadable(params.bufname) == 1
        end,
    },
})

内容的提问来源于stack exchange,提问作者haulvulgar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 20:55:23