Python Type Hints - Annotate Variables, Functions & Classes (Tutorial #29)
Video: Python Type Hints - Annotate Variables, Functions & Classes (Tutorial #29) by Taught by Celeste AI - AI Coding Coach
Watch full page →Python Type Hints - Annotate Variables, Functions & Classes
Type hints in Python help you write clearer, more maintainable code by explicitly specifying the expected types of variables, function parameters, and return values. Using the built-in typing module, you can annotate complex data structures and improve static analysis with tools like mypy.
Code
# Variable annotations
name: str = "Alice"
age: int = 30
height: float = 1.75
is_student: bool = False
# Function with parameter and return type hints
from typing import List, Dict, Optional, Union, Tuple
def greet(person_name: str) -> str:
return f"Hello, {person_name}!"
def average(numbers: List[float]) -> float:
return sum(numbers) / len(numbers)
# Using Optional and Union
def find_user(user_id: int) -> Optional[Dict[str, Union[int, str]]]:
users = {
1: {"id": 1, "name": "Alice"},
2: {"id": 2, "name": "Bob"},
}
return users.get(user_id)
# Type alias for readability
Coordinates = Tuple[float, float]
def distance(p1: Coordinates, p2: Coordinates) -> float:
return ((p2[0] - p1[0])**2 + (p2[1] - p1[1])**2)**0.5
# Example usage
print(greet(name))
print(average([1.5, 2.5, 3.5]))
print(find_user(1))
print(distance((0.0, 0.0), (3.0, 4.0))) # Outputs 5.0
Key Points
- Type hints improve code clarity by explicitly stating expected data types for variables and functions.
- The typing module provides generic types like List, Dict, Optional, Union, and Tuple for complex annotations.
- Type aliases help simplify and clarify complex type annotations for better readability.
- Static type checkers like mypy can detect bugs early by verifying type correctness before runtime.
- Python’s type hints are optional and do not affect runtime behavior but greatly aid development and maintenance.