python-lsp / pylsp-mypy

Mypy plugin for the Python LSP Server.
MIT License
118 stars 35 forks source link

"Cannot find implementation or library stub for module named" error has been persisten with neovim's lspconfig. #84

Open MKrbm opened 4 months ago

MKrbm commented 4 months ago

Error message Cannot find implementation or library stub for module named "module name" always appears whenever I define custom modules.

Screenshot 0006-05-16 at 19 55 27

The minimum example project structure is like below where my_add function is defined in foo.py and the main.py tries to import the function.

lib1/ ├── init.py └── foo.py main.py

import numpy as np
from lib1 import foo

def test(a: int, b: int) -> int:
    return a + b

test(np.ones(3), np.ones(3))

When I run mypy from command line, I can get the expected result

❯ mypy mypy.py
mypy.py:9: error: Argument 1 to "test" has incompatible type "ndarray[Any, dtype[floating[_6
4Bit]]]"; expected "int"  [arg-type]
mypy.py:9: error: Argument 2 to "test" has incompatible type "ndarray[Any, dtype[floating[_6
4Bit]]]"; expected "int"  [arg-type]
Found 2 errors in 1 file (checked 1 source file)

The configuration of the pylsp in my neovim is like

print("python_folder: " .. python_folder)
print("python_executable: " .. python_executable)
print("pylsp_executable: " .. pylsp_executable)

require("lspconfig").pylsp.setup({
    cmd = { pylsp_executable, "--log-file", "/tmp/pyls.log" },
    filetypes = { "python" },
    settings = {
        pylsp = {
            configurationSources = { "flake8" },
            plugins = {
                -- formatter options
                black = { enabled = false },
                autopep8 = { enabled = true },
                yapf = { enabled = false },
                -- linter options
                flake8 = { enabled = true },
                pyflakes = { enabled = false },
                pycodestyle = { enabled = false },
                -- type checker
                pylsp_mypy = {
                    enabled = true,
                    overrides = {
                        "--python-executable",
                        python_executable
                    }
                },
                mypy = { enabled = false },
                -- auto-completion options
                jedi_completion = { fuzzy = false },
                -- import sorting
                pyls_isort = { enabled = false },
            },
        },
    },
})

I'been suffering from this bug? for half a year. Is there any solution? Thank you !

Richardk2n commented 2 months ago

You likely want a true somewhere in your overrides. (I really should document that better …) However, this is not the issue at hand. Why are you using the python-executable flag? What happens if you use it from the command line as well?

I guess this could be an issue with having multiple environments. Are you running pylsp in a different environment than your default one/the one you use for the command line invocation?

Susensio commented 1 month ago

I'm having this problem as well. I'm using mypy plugin from mason's virtual environment (not the project virtual environment)

The project virual environment is activated, but I don't know how the two environments work together.

Richardk2n commented 1 month ago

@Susensio You might have to set python-executeable to the project env. Does it work on command line?

adamingas commented 2 weeks ago

I have the same issue. I set the python-executable to vim.env.VIRTUAL_ENV .. "/bin/python/, and it still doesn't work. I also added a true at the end of the overrides list.

Even if i pass a non-existent python-executable, i.e.

overrides = {--python-executable, 'random', true}

I get not errors in the Logs, and mypy keeps giving me the same Cannot find implementation... errors.

Richardk2n commented 1 week ago

@adamingas Does it work on the command line for you?

adamingas commented 1 week ago

Running mypy from the environment it's installed in (a conda environment) with the correct python executable given as argument (the python binary in my project's venv), works as expected.

I also tried importing mypy and running it from an ipython shell, and that works as well.

Richardk2n commented 1 week ago

The pylsp-mypy log should be part of the lsp-server log. Could you please provide that? I would like to know what calls to mypy are made by pylsp-mypy and with what arguments. Also, please provide your config (to check against what is actually passed).

adamingas commented 1 week ago

Cleared logs, opened a python file, cleared sensitive information, and pasted the logs:

[START][2024-09-06 11:58:44] LSP logging initiated
[INFO][2024-09-06 11:58:44] .../vim/lsp/rpc.lua:662 "Starting RPC client"   {  args = { "/Users/u1078811/.local/share/nvim/plugged/copilot.vim/dist/language-server.js", "--stdio" },  cmd = "node",  extra = {    cwd = "/Users/u1078811"  }}
[DEBUG][2024-09-06 11:58:44] .../vim/lsp/rpc.lua:284    "rpc.send"  {  id = 1,  jsonrpc = "2.0",  method = "initialize",  params = {    capabilities = {      textDocument = {        callHierarchy = {          dynamicRegistration = false        },        codeAction = {          codeActionLiteralSupport = {            codeActionKind = {              valueSet = { "", "quickfix", "refactor", "refactor.extract", "refactor.inline", "refactor.rewrite", "source", "source.organizeImports" }            }          },          dataSupport = true,          dynamicRegistration = false,          isPreferredSupport = true,          resolveSupport = {            properties = { "edit" }          }        },        completion = {          completionItem = {            commitCharactersSupport = false,            deprecatedSupport = false,            documentationFormat = { "markdown", "plaintext" },            preselectSupport = false,            snippetSupport = false          },          completionItemKind = {            valueSet = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 }          },          contextSupport = false,          dynamicRegistration = false        },        declaration = {          linkSupport = true        },        definition = {          linkSupport = true        },        documentHighlight = {          dynamicRegistration = false        },        documentSymbol = {          dynamicRegistration = false,          hierarchicalDocumentSymbolSupport = true,          symbolKind = {            valueSet = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26 }          }        },        hover = {          contentFormat = { "markdown", "plaintext" },          dynamicRegistration = false        },        implementation = {          linkSupport = true        },        publishDiagnostics = {          relatedInformation = true,          tagSupport = {            valueSet = { 1, 2 }          }        },        references = {          dynamicRegistration = false        },        rename = {          dynamicRegistration = false,          prepareSupport = true        },        semanticTokens = {          augmentsSyntaxTokens = true,          dynamicRegistration = false,          formats = { "relative" },          multilineTokenSupport = false,          overlappingTokenSupport = true,          requests = {            full = {              delta = true            },            range = false          },          serverCancelSupport = false,          tokenModifiers = { "declaration", "definition", "readonly", "static", "deprecated", "abstract", "async", "modification", "documentation", "defaultLibrary" },          tokenTypes = { "namespace", "type", "class", "enum", "interface", "struct", "typeParameter", "parameter", "variable", "property", "enumMember", "event", "function", "method", "macro", "keyword", "modifier", "comment", "string", "number", "regexp", "operator", "decorator" }        },        signatureHelp = {          dynamicRegistration = false,          signatureInformation = {            activeParameterSupport = true,            documentationFormat = { "markdown", "plaintext" },            parameterInformation = {              labelOffsetSupport = true            }          }        },        synchronization = {          didSave = true,          dynamicRegistration = false,          willSave = true,          willSaveWaitUntil = true        },        typeDefinition = {          linkSupport = true        }      },      window = {        showDocument = {          support = true        },        showMessage = {          messageActionItem = {            additionalPropertiesSupport = false          }        },        workDoneProgress = true      },      workspace = {        applyEdit = true,        configuration = true,        didChangeWatchedFiles = {          dynamicRegistration = false,          relativePatternSupport = true        },        semanticTokens = {          refreshSupport = true        },        symbol = {          dynamicRegistration = false,          hierarchicalWorkspaceSymbolSupport = true,          symbolKind = {            valueSet = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26 }          }        },        workspaceEdit = {          resourceOperations = { "rename", "create", "delete" }        },        workspaceFolders = true      }    },    clientInfo = {      name = "Neovim",      version = "0.9.1"    },    initializationOptions = {      editorInfo = {        name = "Neovim",        version = "0.9.1"      },      editorPluginInfo = {        name = "copilot.vim",        version = "1.39.0"      }    },    processId = 44956,    rootPath = vim.NIL,    rootUri = vim.NIL,    trace = "off",    workspaceFolders = vim.NIL  }}
[DEBUG][2024-09-06 11:58:45] .../vim/lsp/rpc.lua:387    "rpc.receive"   {  id = 1,  jsonrpc = "2.0",  result = {    capabilities = {      executeCommandProvider = {        commands = { "github.copilot.didAcceptCompletionItem", "github.copilot.didAcceptPanelCompletionItem" }      },      inlineCompletionProvider = vim.empty_dict(),      notebookDocumentSync = {        notebookSelector = { {            notebook = "*"          } }      },      textDocumentSync = {        change = 2,        openClose = true      },      workspace = {        workspaceFolders = {          changeNotifications = true,          supported = true        }      }    },    serverInfo = {      name = "GitHub Copilot Language Server",      nodeVersion = "20.5.0",      version = "1.223.0"    }  }}
[DEBUG][2024-09-06 11:58:45] .../vim/lsp/rpc.lua:284    "rpc.send"  {  jsonrpc = "2.0",  method = "initialized",  params = vim.empty_dict()}
[DEBUG][2024-09-06 11:58:45] .../vim/lsp/rpc.lua:284    "rpc.send"  {  jsonrpc = "2.0",  method = "workspace/didChangeConfiguration",  params = {    settings = {      ["github-enterprise"] = {        uri = vim.NIL      },      http = {        proxy = vim.NIL,        proxyStrictSSL = vim.NIL      }    }  }}
[INFO][2024-09-06 11:58:45] .../lua/vim/lsp.lua:1345    "LSP[GitHub Copilot]"   "server_capabilities"   {  server_capabilities = {    executeCommandProvider = {      commands = { "github.copilot.didAcceptCompletionItem", "github.copilot.didAcceptPanelCompletionItem" }    },    inlineCompletionProvider = vim.empty_dict(),    notebookDocumentSync = {      notebookSelector = { {          notebook = "*"        } }    },    textDocumentSync = {      change = 2,      openClose = true    },    workspace = {      workspaceFolders = {        changeNotifications = true,        supported = true      }    }  }}
[DEBUG][2024-09-06 11:58:45] .../vim/lsp/rpc.lua:387    "rpc.receive"   {  jsonrpc = "2.0",  method = "window/logMessage",  params = {    message = "[lsp] GitHub Copilot Language Server 1.223.0 initialized",    type = 3  }}
[DEBUG][2024-09-06 11:58:45] .../vim/lsp/rpc.lua:387    "rpc.receive"   {  id = 0,  jsonrpc = "2.0",  method = "workspace/configuration",  params = {    items = { {        section = "http"      }, {        section = "github-enterprise"      }, {        section = "github.copilot"      } }  }}
[INFO][2024-09-06 11:58:45] ...lsp/handlers.lua:539 "[lsp] GitHub Copilot Language Server 1.223.0 initialized"
[DEBUG][2024-09-06 11:58:45] .../vim/lsp/rpc.lua:403    "server_request: callback result"   {  result = { {      proxy = vim.NIL,      proxyStrictSSL = vim.NIL    }, {      uri = vim.NIL    }, vim.NIL },  status = true}
[DEBUG][2024-09-06 11:58:45] .../vim/lsp/rpc.lua:284    "rpc.send"  {  id = 0,  jsonrpc = "2.0",  result = { {      proxy = vim.NIL,      proxyStrictSSL = vim.NIL    }, {      uri = vim.NIL    }, vim.NIL }}
[INFO][2024-09-06 11:58:53] .../vim/lsp/rpc.lua:662 "Starting RPC client"   {  args = {},  cmd = "/Users/u1078811/mambaforge/envs/nvim/bin/pylsp",  extra = {    cwd = "/Users/u1078811/projects/llm_cohort_summary"  }}
[DEBUG][2024-09-06 11:58:53] .../vim/lsp/rpc.lua:284    "rpc.send"  {  id = 1,  jsonrpc = "2.0",  method = "initialize",  params = {    capabilities = {      textDocument = {        callHierarchy = {          dynamicRegistration = false        },        codeAction = {          codeActionLiteralSupport = {            codeActionKind = {              valueSet = { "", "quickfix", "refactor", "refactor.extract", "refactor.inline", "refactor.rewrite", "source", "source.organizeImports" }            }          },          dataSupport = true,          dynamicRegistration = false,          isPreferredSupport = true,          resolveSupport = {            properties = { "edit" }          }        },        completion = {          completionItem = {            commitCharactersSupport = true,            deprecatedSupport = true,            documentationFormat = { "markdown", "plaintext" },            insertReplaceSupport = true,            insertTextModeSupport = {              valueSet = { 1, 2 }            },            labelDetailsSupport = true,            preselectSupport = true,            resolveSupport = {              properties = { "documentation", "detail", "additionalTextEdits", "sortText", "filterText", "insertText", "textEdit", "insertTextFormat", "insertTextMode" }            },            snippetSupport = true,            tagSupport = {              valueSet = { 1 }            }          },          completionItemKind = {            valueSet = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 }          },          completionList = {            itemDefaults = { "commitCharacters", "editRange", "insertTextFormat", "insertTextMode", "data" }          },          contextSupport = true,          dynamicRegistration = false,          insertTextMode = 1        },        declaration = {          linkSupport = true        },        definition = {          linkSupport = true        },        documentHighlight = {          dynamicRegistration = false        },        documentSymbol = {          dynamicRegistration = false,          hierarchicalDocumentSymbolSupport = true,          symbolKind = {            valueSet = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26 }          }        },        hover = {          contentFormat = { "markdown", "plaintext" },          dynamicRegistration = false        },        implementation = {          linkSupport = true        },        publishDiagnostics = {          relatedInformation = true,          tagSupport = {            valueSet = { 1, 2 }          }        },        references = {          dynamicRegistration = false        },        rename = {          dynamicRegistration = false,          prepareSupport = true        },        semanticTokens = {          augmentsSyntaxTokens = true,          dynamicRegistration = false,          formats = { "relative" },          multilineTokenSupport = false,          overlappingTokenSupport = true,          requests = {            full = {              delta = true            },            range = false          },          serverCancelSupport = false,          tokenModifiers = { "declaration", "definition", "readonly", "static", "deprecated", "abstract", "async", "modification", "documentation", "defaultLibrary" },          tokenTypes = { "namespace", "type", "class", "enum", "interface", "struct", "typeParameter", "parameter", "variable", "property", "enumMember", "event", "function", "method", "macro", "keyword", "modifier", "comment", "string", "number", "regexp", "operator", "decorator" }        },        signatureHelp = {          dynamicRegistration = false,          signatureInformation = {            activeParameterSupport = true,            documentationFormat = { "markdown", "plaintext" },            parameterInformation = {              labelOffsetSupport = true            }          }        },        synchronization = {          didSave = true,          dynamicRegistration = false,          willSave = true,          willSaveWaitUntil = true        },        typeDefinition = {          linkSupport = true        }      },      window = {        showDocument = {          support = true        },        showMessage = {          messageActionItem = {            additionalPropertiesSupport = false          }        },        workDoneProgress = true      },      workspace = {        applyEdit = true,        configuration = true,        didChangeWatchedFiles = {          dynamicRegistration = false,          relativePatternSupport = true        },        semanticTokens = {          refreshSupport = true        },        symbol = {          dynamicRegistration = false,          hierarchicalWorkspaceSymbolSupport = true,          symbolKind = {            valueSet = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26 }          }        },        workspaceEdit = {          resourceOperations = { "rename", "create", "delete" }        },        workspaceFolders = true      }    },    clientInfo = {      name = "Neovim",      version = "0.9.1"    },    initializationOptions = vim.empty_dict(),    processId = 44956,    rootPath = "/Users/u1078811/projects/llm_cohort_summary",    rootUri = "file:///Users/u1078811/projects/llm_cohort_summary",    trace = "off",    workspaceFolders = { {        name = "/Users/u1078811/projects/llm_cohort_summary",        uri = "file:///Users/u1078811/projects/llm_cohort_summary"      } }  }}
[DEBUG][2024-09-06 11:58:53] .../vim/lsp/rpc.lua:284    "rpc.send"  {  jsonrpc = "2.0",  method = "textDocument/didOpen",  params = {    textDocument = {      languageId = "python",      text = "import json\nimport os\nimport time\nimport re\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\n\nimport openai\nfrom openai import AzureOpenAI\nimport pandas as pd\nfrom azure.identity import ClientSecretCredential\nfrom dotenv import load_dotenv\nfrom openai import ChatCompletion\nfrom llm_cohort_summary.data_utils import df_to_natural_language\nfrom llm_cohort_summary.formatter import format_text\n\nfrom llm_cohort_summary.templates.template import CHAT_V4\nfrom llm_cohort_summary.templates.prompt import ChatPromptTemplate, ChatCompletionMessageDict\nfrom llm_cohort_summary.exceptions import AzureAuthError, AzureCredentialsError, ParsingError\nfrom llm_cohort_summary.mlops import custom_logging\nfrom llm_cohort_summary.utils import get_logger\nfrom typing import List, Tuple\n\n\n\    uri = "file:///Users/u1078811/projects/llm_cohort_summary/llm_cohort_summary/summarise_II_async_calls_GPI_seperate.py",      version = 0    }  }}
[DEBUG][2024-09-06 11:58:53] .../vim/lsp/rpc.lua:284    "rpc.send"  {  jsonrpc = "2.0",  method = "textDocument/didFocus",  params = {    textDocument = {      uri = "file:///Users/u1078811/projects/llm_cohort_summary/llm_cohort_summary/summarise_II_async_calls_GPI_seperate.py"    }  }}
[DEBUG][2024-09-06 11:58:55] .../vim/lsp/rpc.lua:387    "rpc.receive"   {  id = 1,  jsonrpc = "2.0",  result = {    capabilities = {      codeActionProvider = true,      codeLensProvider = {        resolveProvider = false      },      completionProvider = {        resolveProvider = true,        triggerCharacters = { "." }      },      definitionProvider = true,      documentFormattingProvider = true,      documentHighlightProvider = true,      documentRangeFormattingProvider = true,      documentSymbolProvider = true,      executeCommandProvider = {        commands = {}      },      experimental = vim.empty_dict(),      foldingRangeProvider = true,      hoverProvider = true,      notebookDocumentSync = {        notebookSelector = { {            cells = { {                language = "python"              } }          } }      },      referencesProvider = true,      renameProvider = true,      signatureHelpProvider = {        triggerCharacters = { "(", ",", "=" }      },      textDocumentSync = {        change = 2,        openClose = true,        save = {          includeText = true        }      },      workspace = {        workspaceFolders = {          changeNotifications = true,          supported = true        }      }    },    serverInfo = {      name = "pylsp",      version = "1.10.0"    }  }}
[DEBUG][2024-09-06 11:58:55] .../vim/lsp/rpc.lua:284    "rpc.send"  {  jsonrpc = "2.0",  method = "initialized",  params = vim.empty_dict()}
[INFO][2024-09-06 11:58:55] .../lua/vim/lsp.lua:1345    "LSP[pylsp]"    "server_capabilities"   {  server_capabilities = {    codeActionProvider = true,    codeLensProvider = {      resolveProvider = false    },    completionProvider = {      resolveProvider = true,      triggerCharacters = { "." }    },    definitionProvider = true,    documentFormattingProvider = true,    documentHighlightProvider = true,    documentRangeFormattingProvider = true,    documentSymbolProvider = true,    executeCommandProvider = {      commands = {}    },    experimental = vim.empty_dict(),    foldingRangeProvider = true,    hoverProvider = true,    notebookDocumentSync = {      notebookSelector = { {          cells = { {              language = "python"            } }        } }    },    referencesProvider = true,    renameProvider = true,    signatureHelpProvider = {      triggerCharacters = { "(", ",", "=" }    },    textDocumentSync = {      change = 2,      openClose = true,      save = {        includeText = true      }    },    workspace = {      workspaceFolders = {        changeNotifications = true,        supported = true      }    }  }}
[DEBUG][2024-09-06 11:58:55] .../vim/lsp/rpc.lua:284    "rpc.send"  {  jsonrpc = "2.0",  method = "textDocument/didOpen",  params = {    textDocument = {      languageId = "python",      text = "import json\nimport os\nimport time\nimport re\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\n\nimport openai\nfrom openai import AzureOpenAI\nimport pandas as pd\nfrom azure.identity import ClientSecretCredential\nfrom dotenv import load_dotenv\nfrom openai import ChatCompletion\nfrom llm_cohort_summary.data_utils import df_to_natural_language\nfrom llm_cohort_summary.formatter import format_text\n\nfrom llm_cohort_summary.templates.template import CHAT_V4\nfrom llm_cohort_summary.templates.prompt import ChatPromptTemplate, ChatCompletionMessageDict\nfrom llm_cohort_summary.exceptions import AzureAuthError, AzureCredentialsError, ParsingError\nfrom llm_cohort_summary.mlops import custom_logging\nfrom llm_cohort_summary.utils import get_logger\nfrom typing import List, Tuple\n\n\n\,      uri = "file:///Users/u1078811/projects/llm_cohort_summary/llm_cohort_summary/summarise_II_async_calls_GPI_seperate.py",      version = 0    }  }}
[DEBUG][2024-09-06 11:58:57] .../vim/lsp/rpc.lua:387    "rpc.receive"   {  jsonrpc = "2.0",  method = "textDocument/publishDiagnostics",  params = {    diagnostics = { {        code = "import-not-found",        message = 'Cannot find implementation or library stub for module named "openai"',        range = {          ["end"] = {            character = 1,            line = 6          },          start = {            character = 0,            line = 6          }        },        severity = 1,        source = "mypy"      }, {        code = "import-not-found",        message = 'Cannot find implementation or library stub for module named "azure.identity"',        range = {          ["end"] = {            character = 1,            line = 9          },          start = {            character = 0,            line = 9          }        },        severity = 1,        source = "mypy"      }, {        message = "See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports",        range = {          ["end"] = {            character = 1,            line = 9          },          start = {            character = 0,            line = 9          }        },        severity = 3,        source = "mypy"      }, {        code = "import-not-found",        message = 'Cannot find implementation or library stub for module named "dotenv"',        range = {          ["end"] = {            character = 1,            line = 10          },          start = {            character = 0,            line = 10          }        },        severity = 1,        source = "mypy"      } },    uri = "file:///Users/u1078811/projects/llm_cohort_summary/llm_cohort_summary/summarise_II_async_calls_GPI_seperate.py"  }}

Note that I can't see the pylsp_mypy logs anywhere in the log file.

My lsp config:

local opts = { noremap=true, silent=true }
vim.keymap.set('n', '<space>e', vim.diagnostic.open_float, opts)
vim.keymap.set('n', '[d', vim.diagnostic.goto_prev, opts)
vim.keymap.set('n', ']d', vim.diagnostic.goto_next, opts)
vim.keymap.set('n', '<space>q', vim.diagnostic.setloclist, opts)

vim.lsp.set_log_level("debug")
-- Use an on_attach function to only map the following keys
-- after the language server attaches to the current buffer
local on_attach = function(client, bufnr)
  -- Enable completion triggered by <c-x><c-o>
  vim.api.nvim_buf_set_option(bufnr, 'omnifunc', 'v:lua.vim.lsp.omnifunc')

  -- Mappings.
  -- See `:help vim.lsp.*` for documentation on any of the below functions
  local bufopts = { noremap=true, silent=true, buffer=bufnr }
  vim.keymap.set('n', 'gD', vim.lsp.buf.declaration, bufopts)
  vim.keymap.set('n', 'gd', vim.lsp.buf.definition, bufopts)
  vim.keymap.set('n', 'K', vim.lsp.buf.hover, bufopts)
  vim.keymap.set('n', 'gi', vim.lsp.buf.implementation, bufopts)
  vim.keymap.set('n', '<C-k>', vim.lsp.buf.signature_help, bufopts)
  vim.keymap.set('n', '<space>wa', vim.lsp.buf.add_workspace_folder, bufopts)
  vim.keymap.set('n', '<space>wr', vim.lsp.buf.remove_workspace_folder, bufopts)
  vim.keymap.set('n', '<space>wl', function()
    print(vim.inspect(vim.lsp.buf.list_workspace_folders()))
  end, bufopts)
  vim.keymap.set('n', '<space>D', vim.lsp.buf.type_definition, bufopts)
  vim.keymap.set('n', '<space>rn', vim.lsp.buf.rename, bufopts)
  vim.keymap.set('n', '<space>ca', vim.lsp.buf.code_action, bufopts)
  vim.keymap.set('n', 'gr', vim.lsp.buf.references, bufopts)
  vim.keymap.set('n', '<space>fr', vim.lsp.buf.format, bufopts)
  vim.keymap.set('n', '<space>e', vim.diagnostic.open_float, bufopts)
end

-- Add additional capabilities supported by nvim-cmp
local capabilities = vim.lsp.protocol.make_client_capabilities()
capabilities = require('cmp_nvim_lsp').default_capabilities(capabilities)

local lspconfig = require('lspconfig')

-- Enable some language servers with the additional completion capabilities offered by nvim-cmp
local servers = {  
    -- 'pyright',
    'pylsp'
}
-- for _, lsp in ipairs(servers) do
--   lspconfig[lsp].setup {
--   }
-- end

mypy_config = {enabled = true}
if vim.env.VIRTUAL_ENV ~=nil then
    mypy_config = {enabled = true, overrides= {true, "--python-executable",vim.env.VIRTUAL_ENV .. "/bin/python"}}
end

lspconfig['pylsp'].setup{
    cmd = {string.sub(vim.g.python3_host_prog,0,-7) .. 'pylsp'}, -- {"/Users/u1078811/mambaforge/envs/nvim/bin/pylsp"},
    on_attach = on_attach,
    capabilities = capabilities,
    pylsp = {
        plugins = {
            ruff = {
                enabled = true,
                unsafe_fixes = true,
                formatEnabled = true,
                format = {'I' , 'F'},
                line_length = 90
            },
            jedi = {
                auto_import_modules = {'pandas','numpy'}
            },
            pylsp_mypy = mypy_config
        }
    }
}
-- lspconfig['ltex'].setup{
--     filetypes = { "bib", "gitcommit", "markdown", "org", "plaintex", "rst", "rnoweb", "tex", "pandoc" ,"vimwiki"}
-- }
lspconfig["jsonls"].setup{
    filetypes = { "json" },
    cmd = {'vscode-json-languageserver', '--stdio'},
}
adamingas commented 1 week ago

Just realised my pylsp config was wrong. The pylsp nested table should be under a settings key. so from

lspconfig['pylsp'].setup{
    cmd = {string.sub(vim.g.python3_host_prog,0,-7) .. 'pylsp'}, -- {"/Users/u1078811/mambaforge/envs/nvim/bin/pylsp"},
    on_attach = on_attach,
    capabilities = capabilities,
    pylsp = {
        plugins = {
            ruff = {
                enabled = true,
                unsafe_fixes = true,
                formatEnabled = true,
                format = {'I' , 'F'},
                line_length = 90
            },
            jedi = {
                auto_import_modules = {'pandas','numpy'}
            },
            pylsp_mypy = mypy_config
        }
    }
}

to

lspconfig['pylsp'].setup{
    cmd = {string.sub(vim.g.python3_host_prog,0,-7) .. 'pylsp'}, -- {"/Users/u1078811/mambaforge/envs/nvim/bin/pylsp"},
    on_attach = on_attach,
    capabilities = capabilities,
    settings = {
        pylsp = {
            plugins = {
                ruff = {
                    enabled = true,
                    unsafe_fixes = true,
                    formatEnabled = true,
                    format = {'I' , 'F'},
                    line_length = 90
                },
                jedi = {
                    auto_import_modules = {'pandas','numpy'}
                },
                pylsp_mypy = mypy_config
            }
        }
    }
}

And using this mypy config

mypy_config = {enabled = true}
if vim.env.VIRTUAL_ENV ~=nil then
    mypy_config = {enabled = true, overrides= {true, "--python-executable",vim.env.VIRTUAL_ENV .. "/bin/python"}}
end

Works with the current active venv's python/packages. With that i consider the issue solved for me.