A decorator in Python is a function that takes another function as an argument, extends or modifies its behavior and returns a new function, all without permanently changing the source code of the original function.
Decorators are built directly on top of closures and
*args/**kwargs. You typically apply them using the@decorator_namesyntax right above a function definition.
# 1. Define the decorator
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func() # This runs the original function
print("Something is happening after the function is called.")
return wrapper
# 2. Apply the decorator
@my_decorator
def say_hello():
print("Hello!")
# 3. Call the function
say_hello()
# Something is happening before the function is called.
# Hello!
# Something is happening after the function is called.