Inlay Type Hints: a cool new feature for Python & VS Code

Yesterday, I was playing around with my VS Code settings, which is something normal that I do for fun.

I came across settings for Inlay Type Hints, which is a new feature to me, but apparently has been available since July.

Here’s a quick demo:

Demo of Inlay Type Hints for Python in VS Code

You can see that Pylance (VS Code’s Python language server) now displays inferred types for function returns and variables that have not been explicitly type annotated.

The user experience is good but I have a few ideas for improvements:

  • It would be great if type inlays had color/mouse-over information before being inserted,
  • and if types were also automatically imported when inserted.

For now, I have function return annotation enabled all the time, and turn variable annotation on and off depending on what I’m doing – it can be a bit spammy in dense code, but it’s invaluable for debugging. (It would also be nice to be able to toggle annotations with a click!)

Overall, I think this a really cool feature. It underlines the big improvements in Python tooling – by VS Code in particular – that have been made possible by the gradual introduction of type annotation support to the language.

Timeline of changes to type annotations from Python 3.0 to 3.10.
Source: Towards Data Science

Python & VS Code: make Black and organize imports work together on save

Hello world. What a stable and positive time to be alive!

But at least we can fix our code editors.

I use Black to format my Python code, and I tell VS Code to organise imports on save.

Here’s the relevant bit of VS Code’s settings.json:

{
    "python.formatting.provider": "black",
    "editor.formatOnSave": true,
    "editor.codeActionsOnSave": {
        "source.organizeImports": true
    }
}

It’s a pretty pleasant experience, mostly. But this “flapping” behaviour when I save has been bugging me for weeks:

(It’s even more annoying when you’re part way down a file and the entire screen jerks up and down.)

Clearly, Black and the organize imports thing are fighting. But what is the organize imports thing? And what’s the fix?

It turns out that VS Code uses the isort library to sort imports, and isort has a Black compatability profile.

As a Poetry user, all I had to do is add these lines to the pyproject.toml file at the root of my project:

[tool.isort]
profile = "black"

Alternatively, create a file called .isort.cfg (note the leading dot) at the root of your project, with this content:

[settings]
profile=black

No more flapping, and at least one small corner of the universe is a little more sane.