By using Black, you agree to cede control over minutiae of hand-formatting. In return, Black gives you the speed and freedom about your python code formatting. Black makes code review faster by producing the smallest diffs possible.
Here in this doc I'll walk you through the setup of Black in VSCode and PyCharm code editor's.
Install Black in your virtual environment:
$ pip install black
Install Microsoft's Black extension in VSCode:
The bundled black is only used if there is no installed version of black found in the selected python environment.
You can do this either by using the context menu (right click on a open python file in the editor) and select "Format Document With...", or you can add the following to your settings:
"[python]": {
"editor.defaultFormatter": "ms-python.black-formatter"
}
and change the following, if set:
"python.formatting.provider": "none"
You can enable format on save for python by having the following values in your settings:
"[python]": {
"editor.defaultFormatter": "ms-python.black-formatter",
"editor.formatOnSave": true
}
You need to setup External tools.
- File > Settings > Tools > External Tools
- Click on the “+” icon
- Mention your desired Name in the Name input, and give it some description.
- In tool settings, update as following
- Click on “OK”
Now, you’ve done the basic setup of Black and you can now format any file by going on Tools > External Tools ( Your Group name, mine is Linter) > Black.
Additionally you could create a shortcut on PyCharm’s for formatting file with Black by configuring a keymap.
With this Ctrl+Alt+Shift+L; shortcut we can now call the script to format the file.
To setup format on save, we need to goto settings again:
- File > Settings > Tools > File Watchers
- Click on the “+” icon.
- Select “custom”
In the dialog box which appears,
- Input Name of your choosing in “Name”
- In File type select “Python”
- In ‘tool to run on changes’ input following
Program: $PyInterpreterDirectory$/black
Arguments: $FilePath$
Output paths to refresh: $FilePath$
Working directory: $ProjectFileDir$
- Click on “OK” and you’re good to go.
Now just restart your PyCharm instance and you can witness the “Black” magic. 🥂