Neovim and Python

stefanlogue

Stefan Logue

Posted on November 1, 2024

Neovim and Python

Let's face it, working with Python can be a pain at the best of times.

As I used virtual environments to make working with multiple projects with differing Python versions bearable, I had some trouble getting Neovim to find my formatters and linters (black and flake8).
The problem

As my LSP was accessing the Python version within each respective project's virtual environment, I found I was having to install the same packages in each one, and they were packages I should have been able to install globally and not had them tied to individual projects.

I found very little info online about solutions to this issue (maybe people don't use virtual environments the way I do?).
My solution

Using pyenv-virtualenv, I created a virtual environment with the latest Python version specifically for Neovim, in my home directory:

pyenv virtualenv 3.10.12 nvim3.10
Enter fullscreen mode Exit fullscreen mode

Next, I activated the virtual environment, and installed some relevant packages:

pyenv activate nvim3.10
pip install neovim black flake8
Enter fullscreen mode Exit fullscreen mode

Now for the important bit. In my init.lua, I pointed Neovim at the newly created virtual environment, meaning it would use that for LSP things like linting and formatting:

local user = os.getenv("USER")
vim.g.python_host_prog = "/Users/" .. user .. "/.pyenv/versions/nvim3.10/bin/python"
vim.g.python3_host_prog = "/Users/" .. user .. "/.pyenv/versions/nvim3.10/bin/python"
Enter fullscreen mode Exit fullscreen mode

And that's it! A fully working Python setup in Neovim.

💖 💪 🙅 🚩
stefanlogue
Stefan Logue

Posted on November 1, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related