Solution: Creating Function Decorators
Learn how to create a simple function decorator.
We'll cover the following...
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 mathimport time# Creating the decorator functiondef time_taken(func):# Defining the inner functiondef inner(arg):# Calculating and printing execution time of the functionbegin_time = time.time()func(arg)end_time = time.time()print("Time taken by the function: ", end_time - begin_time)# Returning the inner functionreturn inner# Creating the function upon which we'd like to implement our decorator@time_taken # Applying decorator to our functiondef calculate_sqrt(number):square_root = math.sqrt(number)print("Square root of ", number, "is", square_root)# Defining the main() functionif __name__ == "__main__":num = 581529781561# Decorating calculate_sqrt with time_taken### Call to time_taken removed# Calling calculate_sqrtcalculate_sqrt(num)