A decorator in Python is a special function that allows you to modify or enhance the behavior of another function without changing its code.
They are often used for logging, authentication, performance monitoring, or input validation.

Decorators wrap another function inside themselves, execute some code before or after the wrapped function runs, and then return the result.


🧩 Example 1: Logging Function Calls

def log_decorator(func):
    def wrapper(*args, **kwargs):
        print(f"Function '{func.__name__}' called with arguments: {args} {kwargs}")
        result = func(*args, **kwargs)
        print(f"Function '{func.__name__}' returned: {result}")
        return result
    return wrapper

@log_decorator
def add(a, b):
    return a + b

add(3, 5)

Output:

Function 'add' called with arguments: (3, 5) {}
Function 'add' returned: 8

🧩 Example 2: Timing a Function

import time

def timer_decorator(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"{func.__name__} executed in {end_time - start_time:.4f} seconds")
        return result
    return wrapper

@timer_decorator
def slow_function():
    time.sleep(2)
    print("Finished slow function")

slow_function()

Output:

Finished slow function
slow_function executed in 2.0003 seconds

🧩 Example 3: Authentication Check

def require_login(func):
    def wrapper(user):
        if not user.get("is_logged_in"):
            print("Access Denied: User not logged in.")
            return
        return func(user)
    return wrapper

@require_login
def dashboard(user):
    print(f"Welcome {user['name']}! Accessing dashboard...")

user1 = {"name": "Dheeraj", "is_logged_in": True}
user2 = {"name": "Guest", "is_logged_in": False}

dashboard(user1)
dashboard(user2)

Output:

Welcome Dheeraj! Accessing dashboard...
Access Denied: User not logged in.

💬 Key Takeaways:

  • Decorators use the syntax @decorator_name placed above the function definition.
  • They are used to extend functionality of functions without modifying their code.
  • They work with functions, methods, and even classes.

Scroll to Top