Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 38 ยท Linting, Types and Formatting

pre-commit Hooks for Python Projects

Run linters and formatters automatically before every commit. Learn the .pre-commit-config.yaml format, common hooks, CI usage, and see a working hook runner.

You have a formatter, a linter and a type checker. They only help if people remember to run them, and people forget. The classic result is a pull request with a failing build because of one stray space, and a follow-up commit named "fix lint". Git hooks solve this by running a script at a certain moment, such as just before a commit is created. The pre-commit framework makes hooks easy to share: a single YAML file lists the checks, and everyone who clones the repository gets the same ones.

In this lesson you will read the configuration format, learn the everyday commands, and build a tiny hook runner that really lints and formats staged files. The pre-commit program itself needs Git and a command line, so its commands are shown read-only.

How it works

sequenceDiagram
    participant D as Developer
    participant G as git commit
    participant P as pre-commit
    participant H as Hooks (ruff, black, ...)
    D->>G: git commit
    G->>P: run .git/hooks/pre-commit
    P->>H: run each hook on staged files
    H-->>P: pass or fail (may fix files)
    P-->>G: all passed?
    G-->>D: commit created / commit blocked

A failing hook stops the commit. Hooks that fix files leave the changes for you to stage and commit again.

The hook runs only on the files you are committing (the staged files), so it stays fast even in a large repository.

The configuration file

Create .pre-commit-config.yaml in the repository root:

YAML
repos:
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v5.0.0
    hooks:
      - id: trailing-whitespace
      - id: end-of-file-fixer
      - id: check-yaml
      - id: check-toml
      - id: check-added-large-files
        args: ["--maxkb=500"]

  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.6.9
    hooks:
      - id: ruff
        args: ["--fix"]
      - id: ruff-format

  - repo: https://github.com/pre-commit/mirrors-mypy
    rev: v1.11.2
    hooks:
      - id: mypy
        additional_dependencies: ["types-requests"]
  • repo is a Git repository that defines hooks; rev is the tag or commit to use. Pinning rev makes results reproducible.
  • hooks lists the id values you want from that repository, with optional args, files, exclude and additional_dependencies.
  • pre-commit creates an isolated environment for each repository, so the tools do not have to be installed in your project environment.

The version numbers above are examples; run pre-commit autoupdate to move every rev to the latest tag.

Local hooks

You can also run a command from your own environment with a local repository, which is handy for project-specific checks or tools that need your dependencies (like pytest or a type checker that must see installed packages):

YAML
  - repo: local
    hooks:
      - id: pytest-quick
        name: quick tests
        entry: python -m pytest -x -q tests/unit
        language: system
        pass_filenames: false
        stages: [pre-push]

pass_filenames: false runs the command once instead of once per file batch, and stages: [pre-push] moves slower checks to git push so commits stay fast.

Everyday commands

Terminal
pip install pre-commit        # or: uv tool install pre-commit
pre-commit install            # create .git/hooks/pre-commit for this clone
pre-commit run --all-files    # run on everything, e.g. after adding a hook
pre-commit run ruff           # run one hook
pre-commit autoupdate         # bump rev values
git commit --no-verify        # emergency bypass (use rarely)

Everyone must run pre-commit install once per clone, because Git does not copy hooks with the repository. Mention it in your contributing guide. Because hooks can be skipped, also run them in CI; that is the check nobody can bypass:

Terminal
pre-commit run --all-files --show-diff-on-failure

Several services (pre-commit.ci, for example) can run the hooks for you and even push fix commits to pull requests.

A working hook runner

This stand-in does what pre-commit does at heart: read a configuration, take the staged files and run each hook, failing the commit if any check fails. The checks themselves are real: it parses YAML with pyyaml, runs pyflakes on Python files and black in check mode.

Python Run hooks on staged files

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Real pre-commit adds caching, parallelism, per-repository environments and automatic fixing, but the loop above is the idea.

Habits that keep hooks pleasant

  • Keep them fast. A hook that takes thirty seconds will be bypassed. Put slow checks (full test suite, heavy type checks) in CI or the pre-push stage.
  • Make them match CI. The same hook versions locally and in CI mean no surprises.
  • Prefer fixers. A hook that fixes the file (ruff --fix, formatters) is friendlier than one that only complains.
  • Never commit secrets. Hooks such as detect-private-key or secret scanners catch accidents early.
  • Update regularly. pre-commit autoupdate in a scheduled job keeps versions current.

If a hook modifies files, the commit fails on purpose: the fix was not part of what you staged. Run git add -u and commit again. Seeing "files were modified by this hook" is normal, not an error.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should CI also run the pre-commit hooks?

    Local hooks are a convenience that can be bypassed. A CI run is the gate nobody skips.
  2. 2. What does rev mean in .pre-commit-config.yaml?

    Pinning a revision keeps results reproducible; pre-commit autoupdate moves it forward.
  3. 3. A developer clones the repository. What must they do for hooks to run on commit?

    Git does not copy hooks with a repository, so each clone installs them with pre-commit install.
  4. 4. Where should a slow test suite usually run?

    Slow commit hooks get bypassed. Move expensive checks to CI or the pre-push stage.

Summary

  • pre-commit runs checks on staged files before each commit, driven by .pre-commit-config.yaml.
  • Each repo with a pinned rev provides hooks; local hooks run commands from your environment.
  • Run pre-commit install per clone, run --all-files after changes, and autoupdate to bump versions.
  • Always run the same hooks in CI, keep them fast, and let fixers fix.

Next: Testing with pytest