Course contentsShow
← Python
Lesson 590 of 1,0609. Type Safety and Code QualityFree lesson

Automating Code Quality with Pre-commit Hooks

Install and configure the pre-commit framework to execute automated checks immediately before every local git commit operation.

In this lesson, you will learn how to automate your code quality checks by configuring the pre-commit framework to run tasks like Mypy and Ruff automatically before every local git commit.

The Problem with Manual Checks

Up until now, you have been running tools like mypy or ruff manually from your terminal. While this is effective, it is prone to human error—it is easy to forget to run the linter or the type checker before pushing your changes to a repository. This often leads to failed CI builds or "dirty" commits that require a follow-up fix.

The Pre-commit Solution

The pre-commit framework acts as a gatekeeper. By installing it in your project, you define a set of "hooks" that trigger automatically every time you run git commit. If a check (like a type error identified by Mypy or a style violation flagged by Ruff) fails, the commit is blocked, ensuring that only high-quality, validated code enters your version control history.

To set this up, you first install the framework:

pip install pre-commit

Then, you define your configuration in a file named .pre-commit-config.yaml in your root directory:

repos:
-   repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.1.0
    hooks:
    -   id: ruff
-   repo: local
    hooks:
    -   id: mypy
        name: mypy
        entry: mypy
        language: system
        types: [python]

Installing the Hooks

After creating the configuration file, you must install the hooks into your local git environment by running:

pre-commit install

From this point forward, every git commit command will trigger these tools. If Mypy finds a type inconsistency or Ruff finds a syntax issue, the commit will stop, providing you with the exact output from the tool so you can fix the problem before finalizing your commit. This cycle enforces discipline and ensures your project's pyproject.toml standards are always met.

Key Takeaway: Pre-commit hooks automate your code quality workflow by preventing any code that fails your predefined Mypy or Ruff standards from ever being committed to your repository.