Phase 14 of 25 · Topic 14.2

Static Type Checking with Mypy Strict Mode

1Concept

`mypy` is the official static type analyzer for Python. Running with `--strict` enforces explicit return types, disallows untyped definitions, flags implicit Optionals, and verifies generic covariance/contravariance.

2Architecture Diagram

Source Code ---> [ Mypy Static Type Checker ] ---> Catches TypeErrors at CI build time!

3Code Example

Python 3.12
# Mypy verified type signature
def calculate_discount(price: float, discount_pct: float) -> float:
    if not (0.0 <= discount_pct <= 1.0):
        raise ValueError("Discount must be between 0.0 and 1.0")
    return price * (1.0 - discount_pct)

discounted = calculate_discount(150.0, 0.2)
print(f"Discounted Price: ${discounted:.2f}")

4Expected Output

Discounted Price: $120.00

5Key Takeaways

  • Configure `strict = true` in `pyproject.toml` under `[tool.mypy]` for enterprise projects.
  • `cast(TargetType, val)` overrides mypy when dynamic code is known to be safe.
  • Type stubs (`.pyi` files) define type signatures for untyped C extensions.