-- Leo's gemini proxy

-- Connecting to capsule.usebox.net:1965...

-- Connected

-- Sending request

-- Meta line: 20 text/gemini; charset=utf-8; lang=en

Python type annotations and LSP


Posted Sun 25 Apr, 2021.


I'm working on a new project using Python and it is a bit "complicated" (recursion involved, and is in a field I don't have a lot of experience). So I thought I would give type annotations a go, and so far I've found 3 obscure bugs, so I'm keeping it!


I'm using neovim with LSP (via vim-lsc) and Python Language Server with a "mypy" plugin (the tool that checks the type annotations), so I'm going to share some notes here.


First install "pyls" if you don't have it already (any modern pip should install this in your $HOME/.local; don't use sudo!):


pip3 install --upgrade python-language-server[all]

Then install the "mypy" plugin, so we have the type annotations support added:


pip3 install pyls-mypy

And finally enable the plugin using the vim-lsc configuration (and this part was tricky), on your ".vimrc" (or "init.vim" if, like me, you use neovim):


let g:lsc_server_commands = {
 \ 'python': {
 \     'command': 'pyls',
 \     'message_hooks': {
 \         'initialize': {
 \             'initializationOptions': {
 \                 "pyls.plugins.pydocstyle.enabled": 1,
 \                 "pyls.plugins.epyls_mypy.enabled": 1,
 \                 "pyls.plugins.epyls_mypy.live_mode": 0
 \             }
 \         }
 \     }
 \  }
 \ }

And that's all, really!


If you go over a method invocation and use the "hover" command (default is K), for example, you get the method signature with the type annotations and the docstring (if any), and if there's any type discrepancy at any time, you get the appropriate error information inline, which is fantastic!


I'm very happy with the result. I'm not saying that adding all those annotations to the existing code was fun, but spending most of my day job writing Scala, writing those annotations from now on will be easy, and it will pay off when the project grows in code and complexity. So WIN!


Back to the index

Back home


-- Response ended

-- Page fetched on Fri Mar 29 05:13:03 2024