Lesson 8 of 20

Data Structures for AI

Type Hints

3 min read

Type hints make your code self-documenting and help catch bugs before runtime. Modern AI frameworks use them extensively.

Basic Type Hints

# Variable annotations
name: str = "Claude"
temperature: float = 0.7
max_tokens: int = 1000
is_streaming: bool = True

# Function annotations
def greet(name: str) -> str:
    return f"Hello, {name}!"

def add(a: int, b: int) -> int:
    return a + b

Collection Types

from typing import List, Dict, Tuple, Optional

# List of strings
messages: List[str] = ["Hello", "World"]

# Dictionary with string keys and any values
config: Dict[str, any] = {"model": "gpt-4", "temp": 0.7}

# Typed dictionary
settings: Dict[str, str] = {"model": "gpt-4"}

# Tuple with specific types
point: Tuple[int, int] = (10, 20)

# List of dictionaries (common in AI)
chat_history: List[Dict[str, str]] = [
    {"role": "user", "content": "Hi"},
    {"role": "assistant", "content": "Hello!"}
]

Optional and Union

from typing import Optional, Union

# Optional: can be the type or None
def get_user(id: int) -> Optional[str]:
    if id == 1:
        return "Alice"
    return None

# Union: can be multiple types
def process(data: Union[str, bytes]) -> str:
    if isinstance(data, bytes):
        return data.decode()
    return data

# Python 3.10+ syntax (cleaner)
def process(data: str | bytes) -> str:
    ...

Function Signatures in AI Code

from typing import List, Dict, Optional, Callable

# Message type alias
Message = Dict[str, str]

def chat_completion(
    messages: List[Message],
    model: str = "gpt-4",
    temperature: float = 0.7,
    max_tokens: Optional[int] = None,
    on_token: Optional[Callable[[str], None]] = None
) -> str:
    """Generate a chat completion."""
    ...

# Using type aliases for clarity
ApiResponse = Dict[str, any]
ToolResult = Dict[str, str]

def execute_tool(name: str, args: Dict[str, any]) -> ToolResult:
    ...

Benefits of Type Hints

Benefit Description
Documentation Code explains itself
IDE support Better autocomplete and error detection
Bug prevention Catch type errors before runtime
Refactoring Safer code changes

Important Notes

  • Type hints are optional and don't affect runtime
  • Python doesn't enforce types (use mypy for checking)
  • Start simple, add hints gradually
  • Modern Python (3.9+) allows list[str] instead of List[str]

You've completed the Data Structures module! Next, we'll learn about functions and classes. :::

Quiz

Module 2: Data Structures for AI

Take Quiz