[Science, Technology, Engineering, Arts and Maths]

Python: black and flake8 pre-commit hooks

logos of python,black and text for flake8

I like to use pre-commit hooks in my code before git commits. They are handy for automatic clean-up and to highlight possible issues. Most commonly I use flake8 and black.

This can be done as follows. Firstly you will need to install the necessary packages. Type the following 3 lines into the command line:

pip install pre-commit
pip install flake8
pip install black

Next, create (or update your existing) pre-commit-config.yaml file in the base directory of your repo. It should include the following (updated as necessary to accommodate whatever versions of black, python and flake you have installed on your machine.

# .pre-commit-config.yaml
repos:
-   repo: https://github.com/psf/black
rev: 22.3.0
hooks:
- id: black
language_version: python3.10
-   repo: https://github.com/pre-commit/pre-commit-hooks
rev: v2.3.0
hooks:
- id: flake8

Some black rules conflict with flake8. To manage this create a .flake8 file. I currently use the following settings to make them both play nicely with one another:

[flake8]
ignore = E501, W503, F403, F401
max-line-length = 79
max-complexity = 18
select = B,C,E,F,W,T4,B9

Finally, once the configuration files are in place run the following commands:

pre-commit install
pre-commit run --all-files