Skip to content

Pre-commit Configuration#

Complete pre-commit hooks setup for Python projects. Automatically formats code, checks for errors, and enforces code quality before commits.

File: .pre-commit-config.yaml#

default_language_version:
  python: python3.10

repos:
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v4.6.0
    hooks:
      - id: trailing-whitespace
      - id: check-json
      - id: check-toml
      - id: check-xml
      - id: check-yaml
      - id: debug-statements
      - id: check-builtin-literals
      - id: check-case-conflict
      - id: detect-private-key

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

  - repo: https://github.com/PyCQA/isort
    rev: 5.13.2
    hooks:
      - id: isort

  - repo: https://github.com/PyCQA/flake8
    rev: 7.0.0
    hooks:
      - id: flake8

Setup Instructions#

# 1. Install pre-commit
pip install pre-commit

# 2. Install git hooks
pre-commit install

# 3. (Optional) Run on all files
pre-commit run --all-files

What It Does#

  • Trailing whitespace - Removes trailing spaces
  • Check JSON/TOML/XML/YAML - Validates file formats
  • Debug statements - Detects leftover debug code
  • Black - Auto-formats Python code
  • isort - Sorts and organizes imports
  • flake8 - Lints code for errors and style issues
  • Detect private keys - Prevents committing secrets

Customization#

Add to .flake8 file:

[flake8]
max-line-length = 88
exclude = migrations,venv,__pycache__

Add to pyproject.toml for Black/isort:

[tool.black]
line-length = 88
target-version = ['py310']

[tool.isort]
profile = "black"
line_length = 88


Copy the entire .pre-commit-config.yaml content above and save it in your project root.