Type Annotations and Generics

advanced level · ~20 min · Module 16: Type Hints & Static Analysis

Improve code clarity, IDE autocompletion, and maintainability with static type annotations.

Learning objectives

  • Annotate function signatures with parameters and return types
  • Use Union, Optional, List, Dict, and TypedDict

Lesson material

Type Hints Syntax

Type hints do not affect runtime execution directly, but enable static analysis tools like mypy.

Example code

from typing import List, Optional

def process_scores(scores: List[float]) -> Optional[float]:
    if not scores:
        return None
    return sum(scores) / len(scores)

print("Average:", process_scores([90.0, 80.0, 100.0]))

Practice exercise: Annotate Function

Define a function `greet_user(name: str, age: int) -> str` returning `f"{name} is {age}"`. Print `greet_user("Sam", 30)`.

Test yourself with the Module 16: Type Hints & Static Analysis quiz →

View the full Python curriculum →