Setting up pre-commit for Python CLI repos
Automating code quality checks is essential for maintaining consistent Project Setup & Dependency Management workflows in Python CLI repositories. This guide delivers a minimal, production-ready configuration targeting Python 3.10+ environments.
1. Install and Initialize pre-commit
Isolate the pre-commit binary from your project dependencies. Use pipx or uv to install it globally. This prevents version conflicts with your project's virtual environment.
Navigate to your CLI repository root and run the initialization command. This creates a .git/hooks/pre-commit symlink that triggers automatically on git commit.
uv tool install pre-commit
pre-commit install
2. Minimal .pre-commit-config.yaml for CLI Projects
CLI tools require strict formatting and static analysis without heavy overhead. The following configuration uses ruff for linting and formatting. It also includes check-added-large-files to prevent binary bloat in distributed packages.
For advanced hook strategies, consult our guide on Pre-commit Hooks for CLI Projects.
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.6.0
hooks:
- id: check-added-large-files
- id: check-toml
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.4.8
hooks:
- id: ruff
args: [--fix]
- id: ruff-format
Declare pre-commit as a development dependency in your pyproject.toml to ensure CI consistency. Modern Python 3.10+ projects should use standard dependency groups.
[project.optional-dependencies]
dev = ["pre-commit>=3.5.0"]
3. Resolving Common CI Execution Errors
When integrating with GitHub Actions, pipelines often fail with ModuleNotFoundError: No module named 'pre_commit' or pre-commit failed with exit code 1. This occurs when the runner lacks the hook dependencies or uses an outdated Python runtime.
Resolve this by explicitly installing the tool before execution. Always run pre-commit run --all-files in your pipeline. Cache the .pre-commit directory to reduce cold-start times.
# GitHub Actions snippet
- name: Run pre-commit
run: |
pip install pre-commit
pre-commit run --all-files
Troubleshooting
| Symptom | Root Cause | Resolution |
|---|---|---|
ModuleNotFoundError: No module named 'pre_commit' | CI environment lacks pre-commit in the active Python environment. | Add pre-commit to dev-dependencies or install it explicitly in the CI step. |
InvalidManifestError during hook execution | Hook revisions in .pre-commit-config.yaml are out of sync with the installed binary. | Run pre-commit autoupdate to fetch compatible hook versions and regenerate the lock state. |