🌱 Junior Track 19 of 20

19. Python Decorators

Extend function behavior cleanly without modifying source code: master first-class functions, closures, `@decorator` syntax, decorator factories, and preserving function metadata with `@functools.wraps`.

👁️ Views: 0
# ==============================================================================
# JUNIOR PYTHON TRACK 19 — DECORATORS & CLOSURES
# ==============================================================================

import functools
import time

# 1. Basic Function Logger Decorator using functools.wraps
def logger(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print(f"[LOG] Calling {func.__name__} with args={args}, kwargs={kwargs}")
        result = func(*args, **kwargs)
        print(f"[LOG] {func.__name__} returned {result}")
        return result
    return wrapper

@logger
def process_data(data_list):
    """Process items in a list and return sum."""
    return sum(data_list)


# 2. Decorator Factory (Decorators with Arguments)
def repeat(num_times: int = 2):
    def decorator_repeat(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            last_result = None
            for _ in range(num_times):
                last_result = func(*args, **kwargs)
            return last_result
        return wrapper
    return decorator_repeat

@repeat(num_times=3)
def notify_user(user_id):
    print(f"Sending notification to User #{user_id}")
    return True


if __name__ == "__main__":
    total = process_data([10, 20, 30])
    notify_user(101)
🌱 Junior Track 19 Master Reference

19. Decorator Patterns & Best Practices

📊 Common Production Decorators

Pattern Name Syntax Purpose & Description
Standard Wrapper @decorator Wraps function with zero decorator arguments.
Decorator Factory @decorator(arg=val) Accepts custom arguments to configure wrapper behavior.
Built-in LRU Cache @functools.lru_cache Caches result of expensive function calls based on arguments.
Class Decorator @dataclass Modifies or enhances class definitions automatically.

⭐ Rate Track 19: Decorators & Higher-Order Functions (1 to 5 Stars)

Your rating is stored directly in the database. Average: 5.0 / 5 (1 rating)

★ ★ ★ ★ ★
← 18. Generators 🌱 Junior Hub Next Module: 20. Context Managers →