🛡️ Python Tutorial — Mypy Static Type Checking

Introduction 🌟

mypy is a popular static type checker for Python. It reads your code, analyzes your type hints, and warns you about type mismatches — long before your program runs.

Note

💡 mypy does NOT run your code — it analyzes it
💡 Helps prevent runtime errors
💡 Enforces type hints in large, real-world codebases
💡 Works perfectly with modern Python typing features

1. Installing mypy 📦

install_mypy.sh

pip install mypy

✔ Install globally or inside a virtual environment

2. Running mypy on a File ▶️

run_mypy.sh

mypy script.py

mypy will analyze script.py and show errors if types don't match.

3. Basic Example — Detecting Type Errors 🚨

basic_example.py

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

result = add("10", 20)  # ❌ wrong type
print(result)

mypy_output.txt

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

✔ mypy catches the error even before running the program

4. Type Checking Variables 🧱

variable_types.py

age: int = "twenty"  # ❌

output.txt

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

5. Using --strict Mode 🔒

For production-grade projects, strict mode provides maximum safety.

strict_mode.sh

mypy --strict app.py
  • ✔ Requires all functions to be typed
  • ✔ Detects missing return statements
  • ✔ Detects untyped variables
  • ✔ Enforces Optional types

6. Optional Types & mypy ⚠️

mypy warns you if you use a value that might be None.

optional_issue.py

from typing import Optional

def get_user() -> Optional[str]:
    return None

name = get_user()
print(name.upper())   # ❌ possible None

output.txt

error: Item "None" of "Optional[str]" has no attribute "upper"

✔ Fix with a None check

optional_fix.py

if name is not None:
    print(name.upper())

7. Type Checking Collections 📦

collections_example.py

nums: list[int] = ["a", "b"]   # ❌ wrong types

8. Mypy with Classes & Methods 🧩

class_example.py

class User:
    def __init__(self, name: str, age: int):
        self.name = name
        self.age = age

u = User("Sathish", "25")  # ❌

output.txt

error: Argument 2 to "User" has incompatible type "str"; expected "int"

9. Using reveal_type() for Debugging 🔍

reveal_type_example.py

x = [1, 2, 3]
reveal_type(x)

mypy_output.txt

note: Revealed type is "builtins.list[builtins.int]"

✔ Great for debugging type inference

10. Ignoring Specific Lines 🙈

ignore_line.py

value: int = "hello"  # type: ignore

✔ Useful when integrating legacy code

11. Type Aliases & mypy 🎭

aliases.py

UserId = int

def get_user(uid: UserId) -> str:
    return "User"

✔ Clearer type standards for large teams

12. mypy + Generics 🔧

generics_example.py

from typing import TypeVar, Generic

T = TypeVar("T")

class Box(Generic[T]):
    def __init__(self, value: T):
        self.value = value

b = Box("hello")
print(b.value.upper())

✔ mypy checks generic types properly

13. mypy Configuration File (optional) ⚙️

mypy.ini

[mypy]
python_version = 3.11
warn_unused_configs = True
ignore_missing_imports = True
strict = True

✔ Place this in project root to configure once

14. Common Real-World Uses 🌍

  • ✔ Large-scale projects (Django, Flask, FastAPI)
  • ✔ Preventing bugs in ML pipelines
  • ✔ Safer refactoring
  • ✔ API data validation
  • ✔ Complex OOP systems

15. mypy + VSCode / PyCharm 🖥️

Both IDEs can run mypy automatically while typing.

Note

💡 Combined with type hints → Real-time error detection

Cheat Sheet 📘

FeatureUsage
Run mypymypy file.py
Strict modemypy --strict file.py
Ignore errors# type: ignore
Show inferred typesreveal_type()
Use config filemypy.ini
Check packagesmypy package/

Best Practices 💡

  • ✔ Always use type hints in function signatures
  • ✔ Enable --strict for serious projects
  • ✔ Use Union, Optional, and TypedDict carefully
  • ✔ Fix incorrect types early — don’t ignore errors
  • ✔ Combine mypy with CI/CD for automated checks

Conclusion 🎉

>>“mypy turns Python into a statically checked language — without losing its dynamic flexibility.” ✨

You now understand Mypy Static Checking clearly! Want the next topic? Try Protocols, Dataclasses, Pydantic, or Unit Testing. Just tell me! 😊