🎀 What is a Decorator in Python?
A decorator in Python is a powerful tool that allows you to modify or enhance the behavior of functions or methods without changing their actual code. Decorators use the @decorator_name syntax and are widely used in logging, access control, memoization, and more.
They are ideal when:
- 🔄 You want to reuse common logic across multiple functions.
- 🔐 You need to add extra functionality like authentication, logging, or timing.
🛠️ Real-Time Use Cases
- 📋 Logging: Automatically log function calls without modifying the original function.
- ⏱️ Timing: Measure how long a function takes to run.
- ✅ Authentication: Add security checks before allowing a function to execute.
- 📦 Memoization: Cache results of expensive function calls (e.g., in data science apps).
- 📚 Web Frameworks: Flask/Django use decorators for routing URLs to views.
💡 Example: Basic Decorator
def my_decorator(func): def wrapper(): print("Before the function runs") func() print("After the function runs") return wrapper @my_decorator def greet(): print("Hello, World!")
greet()
import timedef timing_decorator(func): def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() print(f"⏱️ Execution time: {end - start:.4f} seconds") return result return wrapper@timing_decoratordef long_running_task(): total = 0 for i in range(1, 10_000_000): total += i print("✅ Task Completed.") return total# Call the functionlong_running_task() ✅ Task Completed.⏱️ Execution time: 1.0263 seconds
49999995000000
import datetimedef log_function_call(func): def wrapper(*args, **kwargs): timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') log_entry = ( f"[{timestamp}] 📝 Called function: '{func.__name__}'\n" f"➡️ Arguments: {args}, Keyword Arguments: {kwargs}\n" ) result = func(*args, **kwargs) log_entry += f"✅ Result: {result}\n\n" print(log_entry) # Fix encoding issue by using utf-8 with open("log.txt", "a", encoding="utf-8") as log_file: log_file.write(log_entry) return result return wrapper 💡 How to Use:
Example 1: Login
@log_function_calldef login(username): return f"User '{username}' logged in."login("admin") [2025-06-16 13:35:17] 📝 Called function: 'login'➡️ Arguments: ('admin',), Keyword Arguments: {}✅ Result: User 'admin' logged in. "User 'admin' logged in."
Example 2: API Call
@log_function_calldef get_data(endpoint, id=0): return {"endpoint": endpoint, "id": id}get_data("user", id=101) [2025-06-16 13:35:29] 📝 Called function: 'get_data'➡️ Arguments: ('user',), Keyword Arguments: {'id': 101}✅ Result: {'endpoint': 'user', 'id': 101} {'endpoint': 'user', 'id': 101} - Monitoring Scheduled Job
@log_function_calldef daily_backup(): return "Backup completed successfully."daily_backup()
[2025-06-16 13:35:57] 📝 Called function: 'daily_backup'➡️ Arguments: (), Keyword Arguments: {}✅ Result: Backup completed successfully. 'Backup completed successfully.'
📊 Summary: Decorator Benefits
| Feature | Decorator |
|---|---|
| ♻️ Code Reuse | High — reuse logic across functions |
| ✨ Enhancing Functions | Without changing original function code |
| 📈 Common Use Cases | Logging, timing, auth, web routes |
| 📌 Syntax | Uses @decorator above function |
0