Search⌘ K

Solution: Creating Function Decorators

Explore how to create and apply function decorators in Python, specifically designing a decorator that calculates and displays execution time. Understand the use of inner functions and the decorator syntax to enhance code readability and reuse.

We'll cover the following...

Solution overview

We implement the logic for the decorator time_taken in the following manner:

Python 3.8
import math
import time
# Creating the decorator function
def time_taken(func):
# Defining the inner function
def inner(arg):
# Calculating and printing execution time of the function
begin_time = time.time()
func(arg)
end_time = time.time()
print("Time taken by the function: ", end_time - begin_time)
# Returning the inner function
return inner
# Creating the function upon which we'd like to implement our decorator
@time_taken # Applying decorator to our function
def calculate_sqrt(number):
square_root = math.sqrt(number)
print("Square root of ", number, "is", square_root)
# Defining the main() function
if __name__ == "__main__":
num = 581529781561
# Decorating calculate_sqrt with time_taken
### Call to time_taken removed
# Calling calculate_sqrt
calculate_sqrt(num)

Code explanation

    ...