Learning

Type Hinting & Annotations

Type Hinting & Annotations

Basic Type Hints

python
# Variable annotations name: str = 'Alice' age: int = 25 height: float = 5.9 is_active: bool = True # These are ANNOTATIONS — Python doesn't enforce them! name: str = 123 # No error at runtime!

Function Signatures

python
def greet(name: str) -> str: return f'Hello, {name}' def add(a: int, b: int) -> int: return a + b def process(items: list, threshold: float) -> bool: return any(x > threshold for x in items) # None return type for side-effect functions def log(message: str) -> None: print(f'[LOG] {message}')

Complex Types from typing

python
from typing import List, Dict, Tuple, Set, Optional # List of strings def get_names() -> List[str]: return ['Alice', 'Bob'] # Dict with string keys and int values def word_count(text: str) -> Dict[str, int]: return {w: text.count(w) for w in set(text.split())} # Tuple with specific types def get_bounds() -> Tuple[float, float]: return (0.0, 100.0) # Optional — can be None def find_user(user_id: int) -> Optional[str]: if user_id == 1: return 'Alice' return None # Valid!

Union & Literal Types

python
from typing import Union, Literal # Multiple possible types def process_id(id_val: Union[int, str]) -> str: return str(id_val) # Python 3.10+ syntax def process_id(id_val: int | str) -> str: return str(id_val) # Exact values def set_mode(mode: Literal['dev', 'prod', 'test']) -> None: print(f'Mode: {mode}') # set_mode('staging') # mypy would catch this!

Type Aliases

python
from typing import Dict, List, Tuple # Complex type given a readable name UserData = Dict[str, Union[str, int, List[str]]] Coordinate = Tuple[float, float] Matrix = List[List[float]] def process_user(data: UserData) -> None: pass def distance(p1: Coordinate, p2: Coordinate) -> float: return ((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2) ** 0.5

mypy Tool

bash
# Install: pip install mypy # Run: mypy script.py # script.py: def add(a: int, b: int) -> int: return a + b add('hello', 'world') # mypy: error: Argument 1 has incompatible type "str"
Key Rules
  • •Type hints are ANNOTATIONS only — Python runtime ignores them completely, no enforcement
  • •Use -> None for functions that don't return a value (side effects only)
  • •Optional[X] is shorthand for Union[X, None] — means the value CAN be None
  • •Type aliases improve readability for complex nested types like Dict[str, List[Tuple[int, ...]]]
  • •Use mypy for static type checking BEFORE runtime — catches type errors early
  • •Python 3.10+ supports X | Y syntax instead of Union[X, Y] — use it when available
Your Task

Create a function `analyze_data(numbers: List[int]) -> Dict[str, Union[int, float, List[int]]]` that returns a dict with keys: 'count' (int), 'mean' (float), 'max' (int), 'min' (int), 'above_mean' (List[int]). Create type aliases `NumberList` and `AnalysisResult`. Create a function `search(items: List[str], query: str) -> Optional[int]` that returns the index or None. Add proper type hints to everything.

EditorPython · JSX
PreviewUpdates on Run Tests
Loading preview…
Tests
Should import from typing module
Should define NumberList type alias
Should define AnalysisResult with Union
analyze_data should have parameter and return type hints
search should return Optional[int]
Should have local variable type annotations