Python Interview Questions: Decorators Explained with Real Examples 🐍⚡ #Python #InterviewQuestions
About this lesson
1️⃣ What problem do decorators solve? Decorators allow you to modify or extend the behavior of functions without changing their source code. Instead of rewriting the function, you wrap it with extra functionality. Common real-world uses: logging authentication caching retry logic timing functions API route registration This keeps code clean, reusable, and maintainable. 2️⃣ How decorators work internally Decorators rely on higher-order functions, meaning functions that accept other functions as arguments. Basic structure: def decorator(func): def wrapper(): print("Before function runs") func() print("After function runs") return wrapper Apply it: @decorator def say_hello(): print("Hello!") say_hello() Output: Before function runs Hello! After function runs The decorator wraps the original function with extra logic. 3️⃣ Why frameworks rely heavily on decorators Decorators help frameworks attach metadata or behavior to functions. Example in FastAPI: @app.get("/users") def get_users(): return {"users": []} Here: @app.get("/users") is actually a decorator that registers the function as an API route. Other frameworks using decorators: Flask Django FastAPI Click CLI pytest This is why decorators appear frequently in interviews. 4️⃣ Real production use cases Logging decorator def log_function(func): def wrapper(*args, **kwargs): print(f"Calling {func.__name__}") result = func(*args, **kwargs) print(f"{func.__name__} finished") return result return wrapper Usage: @log_function def add(a, b): return a + b print(add(3, 4)) Output: Calling add add finished 7 Timing decorator (performance measurement) import time def timer(func): def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() print("Execution time:", end - start) return result return wrapper Useful for debu
DeepCamp AI