How to use Ruff, Mypy, Black and Isort in Pre-commit?

python

Python’s not the strictest language, so to have any confidence in your code it needs to be hit with a barrage of checks to ensure it meets some level of quality.

I use the following code quality checks:

These pre-commit hooks will check your code when you try to commit, catching problems before they reach your repository.

Install the Pre-commit hooks

Add the following .pre-commit-config.yaml file to the root of your repository.

default_language_version:
  python: python3.7

repos:
  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.1.8
    hooks:
      - id: ruff
        types: [python]

  - repo: https://github.com/pre-commit/mirrors-mypy
    rev: v0.971
    hooks:
      - id: mypy
        types: [python]
        args: [--strict]

  - repo: https://github.com/ambv/black
    rev: 22.8.0
    hooks:
      - id: black
        types: [python]
        args: [--check]

  - repo: local
    hooks:
      - id: isort
        name: isort
        entry: isort
        language: system
        types: [python]
        args: [--check,--profile=black]

Install Pre-commit and add the git hooks:

pip install precommit
pre-commit install

Notes

See also: How to use Ruff, Mypy, Black, Isort and Pytest in Github Actions?