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.
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_itthat you can use to log the execution time of any functions you wrap with it.
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