Python Mypy Type Check Error Fix
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".
Right
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.tomlfor mypy configuration - Run mypy in CI to catch type errors early
Common Mistakes with mypy type check
- Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- 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
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro