Skip to content

Python Mypy Type Check Error Fix

DodaTech Updated 2026-06-24 2 min read

In this tutorial, you'll learn about Python Mypy Type Check Error Fix. We cover key concepts, practical examples, and best practices.

The Problem

error: Argument 1 to "greeting" has incompatible type "int"; expected "str"

Mypy catches a type mismatch that should have been flagged.

Wrong

def greeting(name: str) -> str:
    return "Hello " + name

greeting(42)  # Type error caught by mypy

Output: error: Argument 1 to "greeting" has incompatible type "int"; expected "str".

Fix the type annotation to accept both str and int:

from typing import Union

def greeting(name: Union[str, int]) -> str:
    return "Hello " + str(name)

greeting(42)  # OK
greeting("World")  # OK

Or use Any for flexible typing:

from typing import Any

def greeting(name: Any) -> str:
    return "Hello " + str(name)

Configure mypy in pyproject.toml:

[tool.mypy]
python_version = "3.11"
strict = true
ignore_missing_imports = true

Expected output: mypy passes with no errors for the corrected code.

Prevention

  • Add type annotations to all function signatures
  • Use pyproject.toml for mypy configuration
  • Run mypy in CI to catch type errors early

Common Mistakes with mypy type check

  1. Mixing let bindings with <- bindings in do notation, producing type errors
  2. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  3. Non-exhaustive pattern matches that compile with warnings then crash at runtime

These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### What is mypy?

Mypy is a static type checker for Python. It analyzes your code for type inconsistencies without running it, catching bugs before they reach production.

What is the difference between mypy and Pyright?

Both are Python type checkers. Mypy is the original reference implementation. Pyright (used by Pylance in VS Code) is faster and has better editor integration.

How do I make mypy ignore a specific line?

Add # type: ignore[arg-type] at the end of the line. Replace arg-type with the specific error code to ignore only that error type.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro