Course contentsShow
← Python
Lesson 192 of 1,0603. Functions and ModularizationFree lesson

Enhancing Functionality Using Decorator Wrappers

Learners will create decorators to modify or extend the behavior of existing functions without directly altering their underlying source code.

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

  1. The Inner Function: The wrapper function contains the new behavior. It calls the original func() right in the middle.
  2. The Return: The my_decorator function returns the wrapper function itself.
  3. The Syntax: Using @my_decorator directly above say_hello is a clean way to tell Python to pass say_hello into the decorator and replace it with the returned wrapper.

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.