๐ท๏ธ Type Hinting
Type hinting helps you document your code and catch errors early.
Mastering this concept will significantly boost your Python data science skills!
๐ป Code Example:
from typing import ( Optional, Union, List, Dict, Tuple, TypeVar, Generic, Protocol, Callable, Any ) from dataclasses import dataclass # 1. Basic annotations def calculate_xp(actions: List[str], multiplier: float = 1.0) -> int: XP = {"login": 10, "challenge": 30, "pebble": 100} return int(sum(XP.get(a, 0) for a in actions) * multiplier) result: int = calculate_xp(["login", "pebble"], multiplier=1.5) print("XP:", result) # 2. TypeVar + Generic โ typed container T = TypeVar("T") class PynfinityStack(Generic[T]): def __init__(self) -> None: self._items: List[T] = [] def push(self, item: T) -> None: self._items.append(item) def pop(self) -> Optional[T]: return self._items.pop() if self._items else None def __len__(self) -> int: return len(self._items) stack: PynfinityStack[str] = PynfinityStack() stack.push("Python"); stack.push("AI") print("Stack pop:", stack.pop()) # AI # 3. Protocol โ structural typing (duck typing with type safety) class Scoreable(Protocol): def get_score(self) -> float: ... @dataclass class Learner: name: str score: float def get_score(self) -> float: return self.score @dataclass class Course: title: str rating: float def get_score(self) -> float: return self.rating def print_score(item: Scoreable) -> None: print(f"Score: {item.get_score():.2f}") print_score(Learner("santoshtvk", 95.5)) # Works! print_score(Course("Infinite Python", 4.9)) # Works! (structurally compatible) # 4. Callable type hint Handler = Callable[[str, int], bool] def run_with_handler(name: str, score: int, handler: Handler) -> None: ok = handler(name, score) print(f"{name}: {'PASSED' if ok else 'FAILED'}") run_with_handler("dhruv", 85, lambda n, s: s >= 70)
Keep exploring and happy coding! ๐ป