What are Type Hints?
Type hints are annotations indicating expected types. They don't affect runtime but help with code clarity and IDE support.
Basic Type Hints
Annotate functions:
def greet(name: str) -> str:
return f"Hello, {name}!"
def add(a: int, b: int) -> int:
return a + b
Variable Annotations
Annotate variables:
age: int = 25
name: str = "Alice"
scores: list[int] = [85, 90, 78]
Complex Types
Use typing module:
from typing import List, Dict, Optional, Union
def process_data(items: List[str]) -> Dict[str, int]:
return {item: len(item) for item in items}
def find_user(id: int) -> Optional[str]:
return users.get(id)
def process(value: Union[int, str]) -> str:
return str(value)
Type Checking
Use mypy:
# Install: pip install mypy
# Run: mypy your_file.py
Benefits
- Documentation: Clear type indication
- IDE support: Better autocomplete
- Maintainability: Easier to understand code
- Error detection: Catch type errors early
Best Practices
- Start simple: Add hints gradually
- Use typing module: For complex types
- Run mypy: Check types regularly
- Don't over-annotate: Some types are obvious
Next Steps
Learn about dataclasses which work well with type hints.