Search code examples
pygamepython-modulepython-venvneovimcoc.nvim

Make `coc-python` and `jedi` autocomplete modules installed in a virtual environment


With the usual coc.nvim + coc-python + jedi setup NeoVim should use system Python modules to run its own plug-ins but Jedi should be able to autocomplete Python modules installed in the active virtual environment. How do I set it up?

I've globally installed NeoVim and pip install-ed Pylint and Jedi. I've installed coc.nvim and coc-python in NeoVim without issues. I have the system Python 3 path in ~/.vimrc:

let g:python3_host_prog = '/bin/python'

and the following in ~/coc-settings.json:

"python.pythonPath": "/bin/python",
"python.jediEnabled": true,
"python.jediPath": "/usr/lib/python3.9/site-packages",
"python.linting.pylintEnabled": true,
"python.linting.pylintPath": "/bin/pylint",
"python.linting.flake8Enabled": false

When I create a virtual environment, activate it, install pygame and then run NeoVim in it:

➜  python3 -m venv myenv && myenv/bin/activate
➜  pip install pygame
➜  nvim

both linter and Python 3 provider work fine. Jedi, however, completes members for local code but doesn't complete pygame's members unless I install pygame outside of the virtual environment as well, i.e.:

➜  deactivate
➜  pip install pygame
➜  myenv/bin/activate
➜  nvim

But having to install every Python module twice beats the purpose of using virtual environment.


Solution

  • Found it. In coc-settings.json:

    "python.pythonPath": "python",
    

    NeoVim has to always use /bin/python but the path passed to Jedi has to point to Python 3 in the virtual environment when it is active and to /bin/python when it isn't. Setting CoC's Python path to just python lets env take care of it:

    ➜  myenv/bin/activate
    ➜  which python
    /home/test/foobar/myenv/bin/python
    ➜  deactivate
    ➜  which python
    /bin/python