12

I am using the pyright LSP in neovim (0.5). It works, but seems to only pick up on packages available in the standard python installation. It does not autocomplete for packages not in the base python, but in my pyenv environment. In VSCode this is quite easily done by selecting the interpreter.

How can I set the virtual environment or pyenv version to be used by Pyright LSP in Neovim?

Mike
  • 3,775
  • 8
  • 39
  • 79

3 Answers3

20

This is not actually an answer, there is this issue in nvim-lsp where they explore some alternatives, it turns out nvim (or pyright, I don't know exactly) don't respect/load pyenv local .python-version file. An alternative is to use regular venv. Using pyenv shell myvenv before running nvim also works, but it goes against the convenience of .python-version file. Maybe there is a way to load the correct venv with some scripts in bashrc/zshrc/config.fish, but again this is not that convenient, IMHO.

https://github.com/neovim/nvim-lspconfig/issues/717

EDIT: Found a good solution

There is a simple way to get pyright work with pyenv virtualenvs:

Create pyrightconfig.json file in root directory of your project, and paste the following, relacing USERNAME and MY-VENV with your user and venv, supposing your pyenv is installed in ~/.pyenv. It adds another file beyond .python-version, but its easy and don't mess with your shell configs.

{
    "venvPath": "/home/USERNAME/.pyenv/versions/",
    "venv": "MY-VENV"
}

You can check full doc here: https://github.com/microsoft/pyright/blob/master/docs/configuration.md

EDIT 2: Checkout this plugin pyenv-pyright I created. With it you can setup pyright to use pyenv venvs with only one command:

pyenv local my-venv
pyenv pyright

or

pyenv pyright my-venv

This will automatically create/update pyrightconfig.json file with the pyenv virtualenv of your choice. Its a convenient way to overcome neovim+pyright+pyenv virtualenvs setup. https://github.com/alefpereira/pyenv-pyright

Alef Pereira
  • 311
  • 1
  • 6
  • 7
    Using `pyrightconfig.json` file works for me too. However, I am using a local `.venv` in the project root so I had to set `venvPath` to '.' and `venv` to '.venv' for it to work – Steve Vermeulen Apr 13 '21 at 00:55
  • 1
    This works! Also (recommended from [this thread](https://github.com/microsoft/pyright/issues/30#issuecomment-478487986)) you should set `exclude = ["./.venv"]`. Note you can also put pyright settings in a `pyproject.toml` under the `tool.pyright` section! – baggiponte Sep 14 '22 at 18:22
1

TLDR;

echo '{ "venvPath": ".", "venv": ".venv" }' >> pyrightconfig.json

It works with the default pyenv and poetry setup.

Lajos
  • 2,549
  • 6
  • 31
  • 38
1

I failed to make other options work, so I use

pyenv shell [virtual_env_name]

and it works for me.

Iman Mirzadeh
  • 12,710
  • 2
  • 40
  • 44