HOLIDAY SALE! Save 50% on Membership with code HOLIDAY50. Save 15% on Mentorship with code HOLIDAY15.

7) Decorators Lesson

Python Decorator Versatility

3 min to complete · By Martin Breuss

In your previous example, you created a decorator and used it to extend one function. What makes decorators useful, however, is that you can use a single decorator to extend multiple functions with the same behavior:

def decorator_func(initial_func):
    def wrapper_func():
        print("wrapper function picked some...")
        return initial_func()
    return wrapper_func

@decorator_func
def prettify():
    print("flowers for you")

@decorator_func
def feed():
    print("apples and potatoes")

prettify()
feed()

Added Functionality

Without needing to add much extra code, you are able to add the logic defined inside your decorator_func() to any new function that you'll define. Any function you wrap with this decorator will now print the message defined in there before calling the function.

Real World Application

One possible real-world application of a basic decorator like this one would be to time the execution time of your functions. Instead of printing a message, you could print the start time before executing your initial_func() and the end time right after it is completed.

Illustration of a lighthouse

Tasks

  • Create a decorator that repeats the output of wrapped functions twice and uses it to extend at least two different functions.
  • Write a decorator called @time_it that you can use to log the execution time of any functions you wrap with it.
Decorations on a wooden board - Photo by https://unsplash.com/@markusspiske Markus Spiske on Unsplash

Photo by Markus Spiske https://unsplash.com/@markusspiske

Soon, you'll look into some more real-world applications of decorators.

Summary: Python Decorators Versatility

  • One decorator function can extend any number of functions with its behavior
  • An example decorator is calculating the execution time of a function