This post is about how to set up black, the popular code formatter for Python projects.
Configuration #
Black offers very little configuration.
You can put the configuration inside pyproject.toml
under the section [tool.black]
:
[tool.black]
# The keys are the long option names what black accept on the command line.
line-length = 100
skip-string-normalization = true
The pyproject.toml
file should be put at the root of the project.
ref:
- basic configuration: https://black.readthedocs.io/en/stable/usage_and_configuration/the_basics.html
- the black style: https://black.readthedocs.io/en/stable/the_black_code_style/current_style.html
Basic usage #
Format the file inplace :
black your_script.py
If we only want to check if the file needs reformat, we can use
--check
:
black --check your_script.py
Show the diffs between old and new file if black were to reformat:
black --diff --color your_script.py
Integration to Editor/IDE #
PyCharm #
For latest version of PyCharm, open settings, and go to Tools --> Black
, you can configure how black should be run for a file.
Visual Studio Code #
Install the
black formatter extension from Microsoft.
Open the command plate (shift + command + P
), and search Open User Settings (JSON)
, and open the user setting.
Add the following config:
"[python]": {
"editor.defaultFormatter": "ms-python.black-formatter",
"editor.formatOnSave": true,
}
Neovim #
For neovim you can use dedicated formatter plugins from here.
You can also use python-language-server and black as the formatter. The detailed configuration can be found here.
CI/CD integration #
GitHub action #
For GitHub action integration, please check the official doc: https://black.readthedocs.io/en/stable/integrations/github_actions.html
Azure DevOps #
For Azure DevOps, we can add a custom step to check the code formatting:
- script: |
pip install black
black --check --diff .
displayName: Check code format with black
Ref:
Ignore the code reformat commit #
Create a file named .git-blame-ignore-revs
in the project root and add the commit that reformat the code:
# reformat the code using black
<the-full-commit-hash>
Then when using git blame, we can provide this to ignore certain commit:
git blame your_script.py --ignore-revs-file .git-blame-ignore-revs
ref: