...

/

Solution: Creating Function Decorators

Solution: Creating Function Decorators

Learn how to create a simple function decorator.

We'll cover the following...

Solution overview

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

Press + to interact
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

    ...