Python pre-commit Configuration: Black, isort, Flake8, and mypy
Configure Python pre-commit hooks with Black, isort, Flake8, and mypy to format code, sort imports, and check linting and types before each commit.
Git hooks are very useful tools that can be used in any project for many cases. Hooks can be run on every commit to verify the code, delete trailing spaces, run tests, etc. One of the tools which I’m using for it is pre-commit.
My favorite use case is checking the style and quality of Python code. It helps to do more detailed code reviews and focus on logic which is very important rather than pointing to the wrong import order.
Recommended tools
- black - very good Python formatter, having very limited configuration options to allow keep code in the same convention improving the readability
- isort - library which helps with organizing imports alphabetically and segregate imports by type
- flake8 - Python linter which includes tools like PyFlakes, pycodestyle, and Ned Batchelder’s McCabe script
- mypy - static typing checker, helps to not forget about type annotations, this one is a little annoying sometimes so be careful with it
Instalation
- Install pre commit hook
pip install pre-commit
- Create a configuration in file
pre-commit-config.yaml
repos:
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v0.800
hooks:
- id: mypy
args: [--no-strict-optional, --ignore-missing-imports]
files: ^(app/|tests/)
- repo: local
hooks:
- id: black
name: black
entry: black
language: system
types: [ python ]
files: ^(app/|tests/)
- id: isort
name: isort
entry: isort
language: system
types: [ python ]
include: ^(app/|tests/)
exclude: '.*/migrations/.*'
args: [
'--line-length=110',
'--multi-line=3',
'--force-grid-wrap=0',
'--trailing-comma',
'--use-parentheses',
'--ensure-newline-before-comments',
]
- id: flake8
name: flake8
entry: flake8
language: system
types: [ python ]
files: ^(app/|tests/)
- Install git hook scripts
pre-commit install
- Run against all files
pre-commit run --all-files
Summary
Copy and paste the config and have fun! Remember that more tools can be used for the configurations. For more use cases please check this repository.