In Python, a function decorator is a design pattern that allows you to modify or extend the behavior of a function or method without changing its code. Decorators provide a clean and reusable way to add functionality to existing functions, such as logging, timing, authentication, or caching.
How Decorators Work
A decorator is essentially a higher-order function that takes another function as an argument, extends its behavior, and returns the modified function. The syntax for applying a decorator to a function uses the @ symbol followed by the decorator name.
Here’s a simple example:
python
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
Output:
code
Something is happening before the function is called.
Hello!
Something is happening after the function is called.
Explanation:
my_decorator is a function that takes another function (func) as an argument.
Inside my_decorator, a wrapper function is defined. This wrapper function executes additional code before and after calling the original function (func).
The @my_decorator syntax applies the decorator to the say_hello function, effectively replacing say_hello with the modified version returned by my_decorator.
Decorators with Arguments
Decorators can also accept arguments. To achieve this, you need to create a decorator factory—a function that returns a decorator function.