๐ Decorators
Decorators allow you to modify the behavior of a function or class.
Mastering this concept will significantly boost your Python data science skills!
๐ป Code Example:
import time import functools # 1. Simple timing decorator def timer(func): @functools.wraps(func) def wrapper(*args, **kwargs): start = time.perf_counter() result = func(*args, **kwargs) elapsed = (time.perf_counter() - start) * 1000 print(f"[timer] {func.__name__} โ {elapsed:.3f}ms") return result return wrapper # 2. Decorator with parameters def retry(max_attempts=3, delay=0.5, exceptions=(Exception,)): def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): for attempt in range(1, max_attempts + 1): try: return func(*args, **kwargs) except exceptions as e: if attempt == max_attempts: raise print(f"[retry] {func.__name__} failed (attempt {attempt}): {e}") time.sleep(delay) return wrapper return decorator # 3. Class-based decorator class cache_result: """Decorator class that memoizes results.""" def __init__(self, func): functools.wraps(func)(self) self._func = func self._cache = {} def __call__(self, *args): if args not in self._cache: self._cache[args] = self._func(*args) return self._cache[args] @cache_result def pynfinity_course_score(user_id: int, course: str) -> float: # Simulate expensive DB lookup return (user_id * 7 + len(course)) % 100 + 50.0 # 4. Stacking decorators (applied bottom-up) @timer @retry(max_attempts=2) def fetch_pynfinity_data(url: str) -> dict: if "invalid" in url: raise ConnectionError("Bad URL") return {"platform": "pynfinity", "url": url} # 5. Using property as a descriptor decorator class PynfinityUser: def __init__(self, name, score): self._name = name self._score = score @property def score(self): return self._score @score.setter def score(self, v): if not 0 <= v <= 100: raise ValueError("Score must be 0โ100") self._score = v @staticmethod def platform() -> str: return "pynfinity.com" user = PynfinityUser("santoshtvk", 80) user.score = 95 print(f"{user._name}: {user.score} on {PynfinityUser.platform()}") print("Score:", pynfinity_course_score(42, "Python")) fetch_pynfinity_data("https://pynfinity.com/api")
Keep exploring and happy coding! ๐ป