Personal Log »

Python and LSP

I wrote a similar post back in April 2021 –on Gemini, that’s obscure!–, but I updated my main Debian box and something broke. Then I revisited it all after I dropped the few projects I still had with Python 2, and it all stopped working –did it ever work Python 3? Not sure–. So there you go, I did it again and I’m documenting it for “the future”.

I use vim-lsc –for now–, because it does a lot out of the box, and with almost zero configuration. Even now that I use nvim-metals for Scala –in neovim–, I have configured most bindings to behave like vim-lsc because I like it. I guess I could investigate the native neovim support for LSP, but I’ve been lazy. vim-lsc is good, but it doesn’t look like it is actively maintained, so take that into account if you want to try this.

The way I’m enjoying Python lately is with:

  • Python LSP Server –this is a community fork of the unmaintained Python Language Server–. This does a lot of things already, even if you only use this, it is a good experience.
  • Mypy –an optional static type checker for Python–, via pylsp-mypy. The code is checked on save.
  • Black –a code formatter; “Any color you like”–, via python-lsp-black. The code is formatted on save.

You can install all this in your local user using pip with:

python3 -m pip install python-lsp-server pylsp-mypy python-lsp-black

This is best with Python 3.8 or later. You may also want to ensure neither yapf nor autopep8 are installed, or black won’t kick in. But you can skip black all together and use yapf –it is also nice, just not as nice–.

I’m not always annotating my code with types –and I should–, specially in old scripts, but in general this is my setup. And all controlled via vim-lsc and this piece of configuration:

let g:lsc_server_commands = {
 \ 'python': {
 \     'command': 'pylsp',
 \     'suppress_stderr': 0,
 \     'workspace_config': {
 \        'pylsp.plugins.pylsp_mypy.enabled': 1,
 \        'pylsp.plugins.pylsp_mypy.live_mode': 0
 \     }
 \  }
 \ }

let g:lsc_auto_map = {'defaults': v:true, 'FindImplementations': ''}
let g:lsc_preview_split_direction = "below"

vim-lsc will start the LSP server only when we edit a Python file. I recommend reading its help to know what are the keyboard bindings to navigate the code, autocomplete, etc.

I hope this doesn’t break again any time soon, specially now that I’m not using the outdated and unmaintained Python LSP server!

Would you like to discuss the post? You can send me an email!