Post

Coding Convention [2]: Black

Prerequisites


[1] Coding-Convention-1-Code-Formatter

Black


Code formatting tool that unifies code style

black-github

0

Installation


1
pip install black

With Command-line

Check if Formatting to edit

1
black --check [file_name or folder_name]

Editing Formatting

1
black [file_name or folder_name]

With VSCode

Install the extension

Extensions (^+⌘+X) > Type ‘Black Formatter’ > Install

Designate to Formatter in VSCode

  • Add to VSCode preferences to run Black as default formatter
    • Go to .vscode/setting.json in the command palette(⌘+shift+P).
    • Add commands below.
1
2
3
  "[python]": {
    "editor.defaultFormatter": "ms-python.black-formatter"
  }

Format on save

Automatically format your Python files on save by setting the editor.formatOnSave setting to true and the editor.defaultFormatter setting to ms-python.black-formatter. You can also enable format on save for Python files only by adding the following to your settings:

1
2
3
4
  "[python]": {
    "editor.defaultFormatter": "ms-python.black-formatter",
    "editor.formatOnSave": true
  }

Settings

1. black-formatter.args

  • Default: []
  • Description
    • Passing arguments to Black to specify the Python file format. string.
    • e.g. “black-formatter.args” = [”–config”, “"]

2. black-formatter.cwd

  • Default: []
  • Description
    • Sets the current working directory used to format Python files to Black.
    • By default, the root directory of the workspace ${workspaceFolder} is used.
    • If set to ${fileDirname}, the parent folder can be used as the working directory.

3. black-formatter.path

  • Default: []
  • Description
    • Path or command to be used by the extension.
    • Array of single or multiple strings.
    • Each argument is provided as a separate string in the array.
    • Setting to [“black”] will use the Black version available in the PATH environment variable. This may slow formatting.
    • e.g. [”~/global_env/black”][“conda”, “run”, “-n”, “lint_env”, “python”, “-m”, “black” ]

4. black-formatter.interpreter

  • Default: []
  • Description
    • Path to the Python executable or command used to start the Black server and child processes.
    • Allows arrays of single or multiple strings.
    • Each argument is provided as a separate string in the array.
    • If set to [], the path to the selected Python interpreter will be used.

5. black-formatter.importStrategy

  • Default: useBundled
  • Description
    • Defines the Black formatter binary.
    • If set to useBundled, the included Black Formatter binary will be used.
    • When set to fromEnvironment, attempts to use the Black Formatter binary and all dependencies available in the currently selected environment.
    • Note: If the extension cannot find a valid Black Formatter binary for the selected environment, it will fallback to using the accompanying binary.
    • The black-formatter.path setting takes precedence over the action of black-formatter.importStrategy.

6. black-formatter.showNotification

  • Default: off
  • Description
    • Controls when notifications are shown by this extension.
    • e.g. onErroronWarningalways and off

7. black-formatter.serverTransport

  • Default: stdio
  • Description
    • Selects the transport protocol to be used by the Black server.
    • When set to stdio, the extension will use the standard i/o streams.
    • When set to pipe, the extension will use a named pipe (on Windows) or Unix Domain Socket (on Linux/Mac).
    • The stdio transport protocol is the default and recommended option for most users.

Options


  • l : Maximum number of characters per line (initial value 88)
  • —diff : Shows the changed parts in the console without changing the file.
  • —color : Colors the changes when using —diff.
  • You can preview changes with black {파일명 또는 폴더명} -l 80 --diff --color.

Git hook Setting


  • Since code editor settings are ultimately a personal choice, it is advisable to avoid attempting to commit unformatted code at the project level.

1. Install pre-commit package

1
pip install pre-commit

2. Generate .pre-commit-config.yaml file

3. Add

1
2
3
4
5
repos:
  - repo: https://github.com/psf/black
    rev: stable
    hooks:
      - id: black

4. pre-commit

  • Install the Git hook script you just wrote above.
1
2
$ pre-commit install
pre-commit installed at .git/hooks/pre-commit

5. Try to commit after disabling the code editor’s automatic formatting.

6. The Git hook script runs, the commit fails, and Black does the formatting.

How to avoid formatting


# fmt : off / on / skip

Code Formatter is usually specified to run automatically when saving a file or creating a commit. However, there are times when you do not want Code Formatter to run. In that case, set as below.

1
2
3
# fmt: off
--- codes excluded from formatting ---
# fmt: on

If you want to avoid formatting only a specific line within the code, you can use # fmt: skip at the end of that line.

References


This post is licensed under CC BY 4.0 by the author.