Skip to main content

Python Code Linter with Black and Flake8

267 words·2 mins

A concise guide for how to configure a Python project with these code formatting tools: black, isort, and flake8.

They will run one after another as a Git pre-commit hook, and you get something like this whenever you make a Git commit:

$ git commit -m "some feature"
black....................................................Passed
isort (python)...........................................Passed
flake8...................................................Passed
...

These are powerful code linters and auto formatters that keeps your Python projects clean, style-consistent, and adhere to the universal PEP 8 - Style Guide for Python Code.

Config files #

First, we add these config files to project root:

New file pyproject.toml:

[tool.black]
line-length = 100

[tool.isort]
profile = "black"
multi_line_output = 3
include_trailing_comma = true
force_grid_wrap = 0
use_parentheses = true
ensure_newline_before_comments = true
line_length = 100

New file .flake8:

[flake8]
max-line-length = 100

New file .pre-commit-config.yaml:

repos:
  - repo: https://github.com/python/black.git
    rev: 22.3.0
    hooks:
      - id: black
        language_version: python3
  - repo: https://github.com/pycqa/isort
    rev: 5.10.1
    hooks:
      - id: isort
        name: isort (python)
  - repo: https://gitlab.com/pycqa/flake8.git
    rev: 3.9.2
    hooks:
      - id: flake8
        additional_dependencies:
          - flake8-black>=0.1.1
        language_version: python3

Install and generate Git pre-commit hook #

Install the Python pre-commit tool as usual (note:preferably within the project’s dedicated Python virtual environment):

pip install pre-commit

Use the tool to generate a new file at <project-root>/.git/hooks/pre-commit

pre-commit install

Voila! Next time you run the command git commit, the pre-commit hook script will kick in. If all checks and auto formats run fine, the commit will follow through! If not, you can follow the error messages to fix the lint errors.

Extra #

To share this pre-commit hook with other team members, see the short Sharing Local Hooks guide.