Mypy: static type checking

RoadmapsPython

Overview

**Memorizable line:** Mypy reads your type hints and warns you if you pass the wrong data type. Python allows you to add type hints to your functions, like `def add(a: int, b: int) -> int:`. But Python itself does not enforce them. If you pass a string to `add`, Python still tries to run it. Mypy is an external tool you run from your terminal: `mypy my_file.py`. ```python def add(a: int, b: int) -> int: return a + b add(10, '20') ``` Mypy acts like a spell-checker for your types. It reads your code without running it (this is called `static checking`). It warns you that `'20'` is a string, not an integer. **Analogy:** Think of Mypy as a traffic cop checking tickets before you board a train. Python lets you board without checking, but Mypy stops you at the gate if your ticket type is wrong.

It catches errors before you even run your program. This prevents your app from crashing in production.

Where used: FastAPI, Pydantic

Why learn this

Code walkthrough

def double(x: int) -> int:
    return x * 2

val: str = '5'
print(double(val))

Focus: print(double(val))

Aha moment

def add(x: int, y: int) -> int:
    return x + y
print(add(1, 2.5))

Prediction: Will Mypy complain about this code?

Common guess: No, because 2.5 is a number.

Mypy WILL complain because 2.5 is a float, and the function explicitly asked for an int.

Common mistakes

Recall questions

Understanding checks

If you run this code normally in Python, what happens?

It crashes with a TypeError because you cannot add a string and an integer.

Python tries to run the code and fails. Mypy would have warned you about this before you even ran it.

Why do we run Mypy before running our tests?

Because Mypy catches type mismatches quickly without needing to execute any code.

Mypy reads the code statically, finding type bugs instantly.

Practice tasks

Fix a type error

Given this code that Mypy complains about, change the function call so Mypy is happy.

Challenge

Write a typed function

Write a function `is_adult(age: int) -> bool` that returns True if age is 18 or older.

Continue learning

Previous: Basic Annotations

Return to Python Roadmap