๐ Python Type Hints โ Write Safer, Self-Documenting Code
Type hints make Python code more readable, catch bugs earlier, and supercharge IDE autocomplete. Introduced in Python 3.5, improved in every version since.
Run mypy or pyright on your codebase to catch type errors before runtime. VS Code's Pylance does this automatically.
๐ป Code Example:
from typing import Optional, Union, List, Dict, Any from dataclasses import dataclass # 1. Basic type annotations def calculate_discount(price: float, discount_pct: float) -> float: return price * (1 - discount_pct / 100) result: float = calculate_discount(999.0, 10) # 899.1 # 2. Optional โ can be None def find_user(user_id: int) -> Optional[Dict[str, Any]]: users = {42: {'name': 'santoshtvk', 'platform': 'pynfinity'}} return users.get(user_id) # Returns dict or None # 3. Union โ accept multiple types (Python 3.10+ use X | Y) def process_score(score: Union[int, float]) -> str: return f"Score: {score:.1f}%" # Python 3.10+ cleaner syntax: def process_score_modern(score: int | float) -> str: return f"Score: {score:.1f}%" # 4. Typed dataclass โ best of both worlds @dataclass class PynfinityUser: name: str score: float = 0.0 is_premium: bool = False courses: List[str] = None def __post_init__(self): if self.courses is None: self.courses = [] user = PynfinityUser(name="dhruv", score=95.5) print(user) # PynfinityUser(name='dhruv', score=95.5, is_premium=False, courses=[])
| Concept | Key Takeaway |
|---|---|
| Optional[X] | X or None โ same as Union[X, None] |
| Union[X, Y] | Accepts X or Y (use X | Y in Python 3.10+) |
| List[str] | A list containing strings |
| Dict[str, int] | A dict with str keys and int values |
| Any | No constraint โ disables type checking for that value |
Keep exploring and happy coding! ๐