In this lesson, you will learn how to use decorator wrappers to extend the behavior of your functions without changing their source code.
The Concept of Decorators
Sometimes you want to add functionality—like logging, timing how long a function takes to run, or checking permissions—to many different functions. Instead of manually adding that code inside every single function (which is repetitive and messy), you can create a "wrapper."
A decorator is a special type of function that takes another function as an argument, wraps it in a new function that adds the extra behavior, and then returns that new function.
A Concrete Example
Imagine you want to print a message whenever a function is called. You can create a decorator to do this:
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
# Using the @ symbol is shorthand for: say_hello = my_decorator(say_hello)
@my_decorator
def say_hello():
print("Hello!")
say_hello()
How it Works
- The Inner Function: The
wrapperfunction contains the new behavior. It calls the originalfunc()right in the middle. - The Return: The
my_decoratorfunction returns thewrapperfunction itself. - The Syntax: Using
@my_decoratordirectly abovesay_hellois a clean way to tell Python to passsay_hellointo the decorator and replace it with the returnedwrapper.
When you run say_hello(), you are actually calling the wrapper function. It executes the first print statement, runs the original say_hello logic, and then finishes with the final print statement. This pattern allows you to "decorate" any number of functions with the exact same logic while keeping your original functions focused on their specific tasks.
Key Takeaway: Decorators allow you to wrap existing functions with extra logic by using a higher-order function that executes code before and after the original function call.