Decorators are a powerful feature in Python that allow you to modify or extend the behavior of functions or methods without changing their actual code. They are functions that wrap another function to enhance or alter its functionality.

Examples

def my_decorator(func):
def wrapper():
print("Decorated")
return wrapper

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

say_hello()

Output

Decorated
Hello!

Features

  • Decorators wrap a function
  • Allows code reusability
  • Decorators are higher-order functions

Advantages

  • Keeps code cleaner and more readable
  • Helps in separating the logic of modifying behavior
  • Enhances code reuse by allowing common functionality

 Uses

  • Used to automatic logging function.
  • To measures the execution time of functions
  • Used to Cache the results of expensive function calls to improve performance.

 

Categorized in: