DEV Community

loading...

VSCode: Using Black to automatically format Python

adamlombard profile image Adam Lombard (he/him) Updated on ・1 min read

Black is "the uncompromising Python code formatter." It can be configured to automatically format your code whenever you save a file in VSCode.

Install Black in your virtual environment:

$ pip install black
Enter fullscreen mode Exit fullscreen mode

Install Microsoft's Python extension in VSCode:

Microsoft's Python extension in VSCode

Open your VSCode settings, by going 'Code -> Preferences -> Settings'.

Search for "python formatting provider" and select "black" from the dropdown menu:

The VSCode settings interface for the "python formatting provider" options

In the settings, search for "format on save" and enable the "Editor: Format on Save" option:
The VSCode settings interface for the "format on save" option

Black will now format your code whenever you save a *.py file.

Before saving:
Code before formatting

After saving:
Code after formatting


More: How to set Black line lengths in VSCode


Images from VSCode using Hyper Term Theme.

Discussion (7)

Collapse
waylonwalker profile image
Waylon Walker • Edited

I generally need to pass in the black path as well. This might be compatibility issues with wsl.

pipx install black
Enter fullscreen mode Exit fullscreen mode

settings.json

  "python.formatting.provider": "black",
  "python.formatting.blackPath": "/home/<user>/.local/bin/black",
Enter fullscreen mode Exit fullscreen mode

additionally you can turn on automatic formatting on save

"editor.formatOnSave": true,
Enter fullscreen mode Exit fullscreen mode

if you don't want automatic formatting on save for every language

  "editor.formatOnSave": false,
  "[python]": {
    "editor.formatOnSave": true,
   },
Enter fullscreen mode Exit fullscreen mode
Collapse
rngallen profile image
Luqman Jr

Thanks
What if I want to override (88) the default chars per line?

Collapse
waylonwalker profile image
Waylon Walker

You can add this to your pyproject.toml, ~/.black, $XDG_CONFIG_HOME/black, or ~/.config/black

[tool.black]
line-length = 88
Enter fullscreen mode Exit fullscreen mode

black.readthedocs.io/en/stable/usa...

Collapse
adamlombard profile image
Adam Lombard (he/him) Author

As an alternative to Waylon's comment regarding config files, you can also configure the line length in VSCode.

Collapse
card profile image
Marc Anthony Card

Thanks for the quick write up Adam. I was recently referred to start using Black and was curious about getting it running with VSC. This is exactly what I was looking for!

Collapse
adamlombard profile image
Adam Lombard (he/him) Author

Glad it was helpful! :)

Collapse
moonsmile profile image
Forem Open with the Forem app