Module 17 of 21 · Advanced Python for AI Development · Intermediate

Type Hints and Static Analysis

Duration: 8 min

Use type hints to write safer, more maintainable AI code that catches errors early.

Type Annotations

Type hints document expected input and output types, making code more readable and enabling static analysis.

from typing import List, Dict, Tuple

def preprocess_data(data: List[float]) -> List[float]:
    """Normalize data to 0-1 range"""
    min_val = min(data)
    max_val = max(data)
    return [(x - min_val) / (max_val - min_val) for x in data]

def train_model(features: List[List[float]], labels: List[int]) -> Dict[str, float]:
    """Train and return metrics"""
    return {"accuracy": 0.95, "loss": 0.05}

data = [1.0, 2.0, 3.0, 4.0, 5.0]
normalized = preprocess_data(data)
print(f"Normalized: {normalized}")

Try it in Google Colab: Open in Colab

Normalized: [0.0, 0.25, 0.5, 0.75, 1.0]

Using mypy for Static Type Checking

mypy validates type hints without running code, catching bugs early.

# Install mypy
pip install mypy

# Check types in your file
mypy your_script.py

💡 Tip: Add type hints to all functions in production AI code for better maintainability and fewer runtime errors.

❓ What is the benefit of type hints?

← Previous Continue interactively → Next →

Related Courses