"Understanding Decorators in Python: Real-World Examples"

#AI #ML #Python #Post4🚀 Decorator in Python, is a special function that modifies or enhances the behavior of another function or method — without permanently changing its code. You can think of a decorator as a wrapper that adds extra functionality around your existing functions. ------------------------------------------------------------- ✅️Real-World Use Cases ------------------------------------------------------------- 📌1. Logging def log(func): def wrapper(*args, **kwargs): print(f"Calling {func.__name__}") result = func(*args, **kwargs) print(f"{func.__name__} finished") return result return wrapper @log def add(a, b): return a + b add(2, 3) 📌2. Authorization (Flask/Django-style) def require_login(func): def wrapper(user): if not user.get("logged_in"): print("Access denied") return return func(user) return wrapper @require_login def view_profile(user): print(f"Welcome {user['name']}") view_profile({"name": "Alice", "logged_in": False}) 📌3. Timing Function Execution import time def timer(func): def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() print(f"{func.__name__} took {end - start:.4f} seconds") return result return wrapper @timer def compute(): sum([i*i for i in range(100000)]) compute() Class-based decorators, which do the same thing as function-based ones — but give you more power and flexibility, especially when you need to store state or maintain configuration across multiple calls. ------------------------------------------------------------- ✅️What is a Class-Based Decorator? ------------------------------------------------------------- A class-based decorator is simply a class that: 📌1. Takes a function in its constructor (__init__) 📌2. Implements the __call__() method, so that the instance can be called like a function 👉This way, when Python sees @MyDecorator, it: 👉Creates an instance of MyDecorator, passing the decorated function to it. 👉Then, every time you call the decorated function, it actually calls MyDecorator.__call__(). ------------------------------------------------------------- ✍️Example 1: Simple Class Decorator ‐------------------------------------------------------------ class MyDecorator: def __init__(self, func): self.func = func # store the original function def __call__(self, *args, **kwargs): print("Before the function runs") result = self.func(*args, **kwargs) print("After the function runs") return result @MyDecorator def say_hello(): print("Hello!") say_hello() ------------------------------------------------------------- 💻Output: ------------------------------------------------------------- Before the function runs Hello! After the function runs

  • diagram

To view or add a comment, sign in

Explore content categories