Setup Black With Vscode Python Python

Jan 31st, 2020 - written by Kimserey with .

Few weeks ago we looked at Prettier, an opinionated formatter for Javascript and Typescript. Formatter allows us to automate the tasks of making sure that the code written is well aligned, readable, and maintainable. As a side effect, it allows all developers to conform to the same formatting rules since it is automatically enforced. In today’s post, we will look at Black, the Python autoformatter.

Install Black

Black formats Python code with an opinionated standpoint. It is not configurable, it does not inherit from other configurations, it does not hint on best format, therefore makes it very explicit and predictable. The biggest benefit from that is that it leaves no room for interpretation or debates as all we need to do is to completely leave the formatting to Black.

Black can easily be installed with pip.

1
pip install black

Then we can directly use it with the black command:

1
2
3
4
(venv) ➜  test-black black test.py
reformatted test.py
All done! ✨ 🍰 ✨
1 file reformatted.

The default rules of Black will be applied.

For more details about the default style code, refer to Black Github repository.

Configure Black on VSCode

For bigger project, it is useful to setup VSCode to use Black automatically on save.

The Python extension comes preinstaller with formatter settings but uses autopep8 as default. To change we can either navigate through the settings UI and change Python > Formatting: Provider to Black. If we installed Black in our virtual environment, the default path to Black is black which should work. Lastly we set the formatting to format on save under Editor > Format On Save. Make sure to click those settings under the Workspace tab so that it will be saved for the current project.

Otherwise all this settings can be manually added to the .vscode/settings.json file:

1
2
3
4
5
{
    "python.pythonPath": "venv/bin/python3",
    "python.formatting.provider": "black",
    "editor.formatOnSave": true
}

And that’s it! Once you save a file, Black will automatically format your content.

External Sources

Designed, built and maintained by Kimserey Lam.