0Pricing
Python Academy · Lesson

Running mypy and Fixing Type Errors

Configure mypy, interpret errors, and incrementally type a codebase.

Running mypy and Fixing Type Errors is a free Python Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Installing and Running mypy

Install mypy with pip and run it on a file or package. It reports type errors without executing your code.

# pip install mypy

# Check a single file:
# mypy script.py

# Check a package:
# mypy mypackage/

# Strict mode (recommended for new code):
# mypy --strict script.py

Your First mypy Error

mypy detects incompatible types, missing return values, and un-annotated function arguments.

# script.py
def add(a, b):   # mypy: Missing type annotation
    return a + b

result: int = add("hello", 1)  # str, not int

# mypy output:
# error: Returning Any from function declared to return "int"

--strict Flag

--strict enables many additional checks: missing annotations, Any usage, untyped imports, etc. Start without it and add gradually.

# Most important strict flags individually:
# --disallow-untyped-defs
# --disallow-any-generics
# --warn-return-any
# --no-implicit-reexport

# Or all at once:
# mypy --strict mypackage/

Ignoring Errors

Add # type: ignore at the end of a line to suppress a specific error. Use sparingly with a comment explaining why.

import third_party  # type: ignore[import]  # no stub available

x: int = get_dynamic_value()  # type: ignore[assignment]

mypy.ini / pyproject.toml Configuration

Store mypy settings in mypy.ini or pyproject.toml so you do not need to pass flags every run.

# mypy.ini
[mypy]
python_version = 3.11
strict = True
ignore_missing_imports = True

[mypy-third_party.*]
ignore_errors = True

Incremental Mode

mypy caches results between runs. Only changed files are re-checked, making subsequent runs fast.

# First run:
# mypy mypackage/   — full analysis, ~5 s

# Second run (nothing changed):
# mypy mypackage/   — Success: no issues in 0 source files (0.3 s)

Common Error: Incompatible Types

The most frequent error: assigning or passing a value of the wrong type.

# error: Incompatible types in assignment
# (expression has type "str", variable has type "int")

count: int = 0
count = "five"   # error

# Fix:
count = 5

Common Error: Argument Type Mismatch

Passing wrong-typed arguments to a function.

def greet(name: str) -> str:
    return f"Hello, {name}"

# error: Argument 1 to "greet" has incompatible type "int"
greet(42)   # error

# Fix:
greet(str(42))

Common Error: Returning None Unexpectedly

A function declared to return a non-None value but has a code path that returns None.

# error: Missing return statement
def find(items: list[int], target: int) -> int:
    for item in items:
        if item == target:
            return item
    # Missing: no return if not found!

# Fix:
def find2(items: list[int], target: int) -> int | None:
    for item in items:
        if item == target:
            return item
    return None

Narrowing with isinstance

Use isinstance to narrow a Union type inside a branch. mypy understands this and narrows the type.

def process(value: int | str) -> str:
    if isinstance(value, int):
        return str(value * 2)   # mypy knows value is int here
    return value.upper()         # mypy knows value is str here

Using cast

typing.cast(Type, value) tells mypy to treat a value as a given type without runtime effect. Use only when you know better than mypy.

from typing import cast

def get_value() -> object:
    return 42

result = cast(int, get_value())   # mypy treats result as int
print(result + 1)   # 43

Quick Check

What does adding # type: ignore to a line do?

Recap

Run mypy script.py to check types. Fix incompatible assignments, argument mismatches, and missing returns. Use isinstance to narrow unions, # type: ignore sparingly, and configure mypy in mypy.ini. Enable --strict gradually.

Frequently asked questions

Is the “Running mypy and Fixing Type Errors” lesson free?

Yes — the full text of “Running mypy and Fixing Type Errors” is free to read here on the web, and the Python Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO.

What will I learn in “Running mypy and Fixing Type Errors”?

Configure mypy, interpret errors, and incrementally type a codebase. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Python Academy?

No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Running mypy and Fixing Type Errors” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Python Academy lesson?

Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Basic Type Annotations
  2. Complex Types: List, Dict, Optional, Union
  3. TypeVar, Generic Classes, and Protocol
  4. Running mypy and Fixing Type Errors
← Back to Python Academy