3

Black Formatter Setup for Python Project

 2 months ago
source link: https://jdhao.github.io/2024/02/22/black_formatter_setup/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Black Formatter Setup for Python Project

2024-02-22313 words 2 mins read 11 times read

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.

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

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

Author jdhao

LastMod 2024-02-22

License CC BY-NC-ND 4.0

Next


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK