Formatting Python in Visual Studio Code with Black

I use Visual Studio Code for all sorts of things both at home and at work - it's the easiest way to edit files while also keeping them synced with git repositories, downloading and running code on microcontrollers and all sorts of other things.

Much of what I write is in Python - I'm by no means an expert, but for someone who grew up with BASIC, it's straightforward enough for me to do the sort of things I want to do.

What I've recently discovered, though, is that there are formatting style guides like PEP 8 for Python code (which already relies on correct indentation of lines to work properly), to make it readable and cogent. I'm often inconsistent with my choice of quotes and spacing, so my code doesn't always look that good.

There's a tool called Black that I've found really helps with this, and it can be installed as an extension in Visual Studio Code. This is a quick guide to how to do this, and - even better - apply the style to Python code every time it's saved.

First, go to the Extensions button on the left of the screen, and search for Black Formatter. The one to choose is the Microsoft one. Click the Install button, and it's ready to go.

To activate automatic formatting when documents are saved, hit CTRL-SHIFT-P to go into the Command Palette, type: Open User Settings Json and hit enter.

Towards the end of the file enter the following:

"[python]": {
    "editor.defaultFormatter": "ms-python.black-formatter",
    "editor.formatOnSave": true
  },

...then save the file. That's it. It'll turn messy, inconsistent code like this:

into something a lot more elegant: