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

Integrating Static Analysis into Git Workflows

Chain Mypy type checking and Ruff linting together within a single pre-commit pipeline to catch errors before code is pushed.

In this lesson, you will learn how to unify your type-checking and linting processes by chaining Mypy and Ruff together in a single pre-commit pipeline.

Why Chain Them?

While you’ve learned to run mypy for type safety and ruff for code style, running them manually is prone to human error. By integrating both into a .pre-commit-config.yaml file, you ensure that every time you run git commit, your code is automatically audited for both logic errors and style violations before it ever reaches your repository.

The Pipeline Configuration

To chain these tools, you define them as "hooks" within your configuration file. Pre-commit executes these hooks in the order they are listed. If either tool finds an error, the commit is blocked, acting as a mandatory "quality gate" for your code.

Create or update your .pre-commit-config.yaml as follows:

repos:
  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.3.0
    hooks:
      - id: ruff
        args: [--fix]
      - id: ruff-format
  - repo: https://github.com/pre-commit/mirrors-mypy
    rev: v1.8.0
    hooks:
      - id: mypy
        additional_dependencies: ['pydantic'] # Include if your code uses typed libraries

How It Works

When you stage your files and run git commit, the pre-commit framework triggers this chain:

  1. Ruff checks for style issues and automatically fixes what it can (via --fix).
  2. Ruff-format ensures your code conforms to a consistent layout.
  3. Mypy runs your strict type-checking suite on the staged files.

If Mypy identifies a type mismatch (like an int passed where a str is expected) or Ruff finds a syntax error, the commit fails. You are then forced to resolve the discrepancy locally, ensuring that only "clean" and "type-safe" code enters your version history. This practice prevents the frustration of "breaking the build" in your CI/CD pipeline, as you catch issues at the very start of the development cycle.

Key Takeaway: By chaining Mypy and Ruff in a pre-commit pipeline, you create an automated, non-negotiable quality gate that validates both type integrity and style consistency every time you commit.