My name is Piotr, a passionate pythonista and this is my blog!

    The best pre-commit config for Python code

    Posted at — Jun 10, 2021

    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.


    1. Install pre commit hook
    pip install pre-commit
    1. Create a configuration in file pre-commit-config.yaml
     - repo:
        rev: v0.800
          - id: mypy
            args: [--no-strict-optional, --ignore-missing-imports]
            files: ^(app/|tests/)
      - repo: local
          - 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: [
          - id: flake8
            name: flake8
            entry: flake8
            language: system
            types: [ python ]
            files: ^(app/|tests/)
    1. Install git hook scripts
    pre-commit install
    1. Run against all files
    pre-commit run --all-files


    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.