Introduction
Type hints annotate variables, function parameters, and return types for better code clarity.
Basic Type Hints
def greet(name: str) -> str:
return f"Hello, {name}"
age: int = 25
prices: list[float] = [1.99, 2.99]
Complex Types
from typing import List, Dict, Tuple, Optional, Union
# Multiple types
def process(x: Union[int, float]) -> Optional[str]:
pass
# Generic types
def sum_list(nums: List[float]) -> float:
return sum(nums)
# Dictionary with types
def word_count(texts: List[str]) -> Dict[str, int]:
return {t: len(t) for t in texts}
# Tuple
def coordinates() -> Tuple[float, float]:
return (1.0, 2.0)
Callable Types
from typing import Callable
def apply(func: Callable[[int], int], value: int) -> int:
return func(value)
# With multiple arguments
def execute(func: Callable[[int, str], bool], a: int, b: str) -> bool:
return func(a, b)
Practice Problems
- Add type hints to a function
- Create TypedDict for complex data
- Use Protocol for duck typing
- Type a decorator
- Define generics with TypeVar