๐ ๏ธ Functools
The functools module is for higher-order functions: functions that act on or return other functions.
Mastering this concept will significantly boost your Python data science skills!
๐ป Code Example:
import functools import time # 1. @lru_cache โ memoize expensive function calls @functools.lru_cache(maxsize=128) def fibonacci(n: int) -> int: """Compute nth Fibonacci โ cached for speed.""" if n <= 1: return n return fibonacci(n - 1) + fibonacci(n - 2) print("fib(40):", fibonacci(40)) print("Cache info:", fibonacci.cache_info()) # CacheInfo(hits=38, misses=41, maxsize=128, currsize=41) # 2. functools.wraps โ preserve metadata in decorators def pynfinity_logger(func): @functools.wraps(func) # Without this, func.__name__ would be "wrapper" def wrapper(*args, **kwargs): print(f"[LOG] Calling {func.__name__}({args}, {kwargs})") result = func(*args, **kwargs) print(f"[LOG] {func.__name__} returned {result}") return result return wrapper @pynfinity_logger def compute_xp(actions: int, multiplier: float = 1.0) -> float: return actions * 10 * multiplier compute_xp(5, multiplier=1.5) print("Function name preserved:", compute_xp.__name__) # 3. functools.partial โ pre-fill arguments def send_notification(user: str, platform: str, level: str, message: str): print(f"[{level.upper()}] @{user} on {platform}: {message}") # Create specialized sender with fixed platform pynfinity_notif = functools.partial(send_notification, platform="pynfinity", level="info") pynfinity_notif("santoshtvk", message="New pebble published!") pynfinity_notif("dhruv", message="Your score improved to 95!") # 4. functools.reduce โ aggregate a sequence from functools import reduce user_scores = [85, 92, 78, 96, 88, 71, 99] total = reduce(lambda acc, x: acc + x, user_scores) product = reduce(lambda acc, x: acc * x, [1, 2, 3, 4, 5]) print(f"\nTotal XP: {total} | Factorial 5: {product}") # 5. functools.cache (Python 3.9+) โ simpler version of lru_cache @functools.cache def power_of_two(n: int) -> int: return 2 ** n print("2^10:", power_of_two(10))
Keep exploring and happy coding! ๐ป