Decorator in Python

 

Decorator in Python

A decorator in Python is a function that modifies the behavior of another function — without changing its actual code.

You can think of decorators as wrappers around functions: they let you add extra functionality before or after a function runs.


📌 Why Use Decorators?

  • Logging

  • Timing function execution

  • Access control

  • Code reuse

  • Input validation


✅ Basic Syntax


@decorator_name def some_function(): # code

✅ Simple Example of a Decorator

🔹 Step 1: Define a Decorator Function


def my_decorator(func): def wrapper(): print("Before the function runs") func() print("After the function runs") return wrapper

🔹 Step 2: Apply the Decorator

@my_decorator
def say_hello(): print("Hello!") say_hello()

Output:

Before the function runs
Hello! After the function runs

✅ Example with Arguments


def debug_decorator(func): def wrapper(*args, **kwargs): print(f"Calling {func.__name__} with arguments {args}") result = func(*args, **kwargs) print(f"{func.__name__} returned {result}") return result return wrapper @debug_decorator def add(a, b): return a + b add(3, 4)

Output:

Calling add with arguments (3, 4)
add returned 7

✅ Real-Life Use: Timing a Function

import time def timer_decorator(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_decorator def long_running_task(): time.sleep(2) print("Task complete") long_running_task()

Output
Task complete
long_running_task took 2.0014 seconds

✅ Summary

TermMeaning
@decorator_name            Syntax to apply a decorator
wrapper()            Inner function that adds extra code
*args, **kwargs            To allow any number of arguments

Comments

Popular posts from this blog

Python For Application Development MNCST 309 KTU BTech CS Minor 2024 Scheme - Dr Binu V P

Course Details MNCST 309 Python For Application Development

Regular Expression