DEV Community

VSCode: Using Black to automatically format Python

Adam Lombard on April 30, 2020

Black is "the uncompromising Python code formatter." It can be configured to automatically format your code whenever you save a file in VSCode. In...
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 • Edited

I'm a fan of using pyproject.toml, but as an alternative to Waylon's comment regarding config files, you can also configure the line length in VSCode.

Collapse
 
attilavm profile image
Attila Molnar

I am just doing a code review and this post was perfect for me to link it inside a comment about an illformted code. Thank you.

Collapse
 
moonsmile profile image
Nguyễn Minh Tuấn

good :D

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

Glad it was helpful! :)

Collapse
 
thealjey profile image
Eugene Kuzmenko

can I use it with *.rpy Ren'Py files?