The most Pythonic and professional way to install pre-commit Git hooks in a Python repository is to use the pre-commit framework. It’s the de facto standard in the Python ecosystem and is widely adopted in open-source and enterprise projects.
✅ Step-by-Step (Pythonic & Professional)
1. Install pre-commit
pip install pre-commit
✅ Best practice: Pin it in your requirements-dev.txt or pyproject.toml under [project.optional-dependencies].
2. Create .pre-commit-config.yaml
At the root of your repo, define your hooks. Example:
# .pre-commit-config.yaml
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.6.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- id: check-added-large-files
- repo: https://github.com/psf/black
rev: 24.4.2
hooks:
- id: black
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: v0.4.7
hooks:
- id: ruff
🔁 Use pre-commit autoupdate to bump versions periodically.
3. Install the Git Hook Scripts
Run this once per clone:
pre-commit install
This installs the hooks into .git/hooks/pre-commit.
4. (Optional) Run Against All Files
To ensure everything is clean:
pre-commit run --all-files
✅ Bonus: CI Integration
Add a GitHub Actions job to enforce pre-commit in CI:
# .github/workflows/pre-commit.yml
name: pre-commit
on:
pull_request:
push:
branches: [main]
jobs:
pre-commit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.11'
- uses: pre-commit/action@v3.0.1
✅ Summary Checklist
| Task | Command |
|---|
| Install | pip install pre-commit |
| Config | .pre-commit-config.yaml |
| Install hooks | pre-commit install |
| Run all | pre-commit run --all-files |
| CI | Use pre-commit/action@v3.0.1 |
This approach is standardized, maintained, and widely supported across the Python ecosystem.