Skip to main content
🛡️ Verified Technical Content: Written by Serhii Hrekov. | Last reviewed & updated in Git: February 19, 2026

Setting up pre-commit in python project

· 3 min read
Serhii Hrekov
Senior Software Engineer & System Architect specializing in Python, Web Systems, Cloud Infrastructure & Automation

Tools like pre-commit help ensure all checks (type checking, linting, formatting, etc.) are run before code is committed. It integrates easily with Git and runs defined hooks automatically when git commit is executed.


Why Use pre-commit?​

  • Catch issues early (before code hits CI or production)
  • Enforce consistent formatting and style
  • Automate repetitive checks (e.g., black, flake8, mypy)
  • Save time during code review

Step-by-Step Setup​

1. Install pre-commit​

pip install pre-commit

2. Create the .pre-commit-config.yaml File​

This file must be placed at the root of your Git repository.

Example configuration:

repos:
- repo: https://github.com/psf/black
rev: 24.3.0
hooks:
- id: black

- repo: https://github.com/pycqa/flake8
rev: 6.1.0
hooks:
- id: flake8

- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.9.0
hooks:
- id: mypy

3. Install the Git Hook Scripts​

Run this once to install hooks:

pre-commit install

Now every time you try to git commit, your configured hooks will run first.


4. Run Checks Manually (Optional)​

If you want to run all hooks against all files manually:

pre-commit run --all-files

Best Practices​

  • Add .pre-commit-config.yaml to your repo
  • Add pre-commit to your requirements.txt or pyproject.toml
  • Include it in onboarding docs for contributors
  • Use consistent versions of hooks with rev: pinning
  • Use it alongside tox, pytest, mypy, etc.

Further Reading​