Monday, January 24, 2022

What are Function Decorators and how to define them in Python Program

How to define Function Decorators in Python Program
In Python, we can extend and modify the behavior of a callable functions, methods or classes without permanently modifying(eg: the original definition of the function as it is) the callable by using decorators.
The Function decorators are functions which accepts function references as arguments and adds a decorator or wrapper or additional functionality around them and returns the function with the additional(wrapper) features as a new function.
To apply the decorator(wrapper function) to any function, we can use the '@' symbol along with the decorator function name just before the actual function for which you wants to apply.
Example:
Now lets define a decorator(wrapper) function which helps to find the total time taken for the execution of a function.

import time

def exe_time(func):  # Outer function
    def wrapper(*args, **kwargs):  # Inner function
        st_time = time.time()
        result = func(*args, **kwargs)
        en_time = time.time()
        print('The execution time of '+ func.__name__ + ' is: ' + str(round((en_time-st_time)*1000, 2))+' milli sec.')
        return result
    return wrapper

Now we can use this exe_time() function as a decorator to the following functions.

@exe_time  # Decorator or wrapper function
def func_square(n):  # The original Function
    x = []
    for k in n:
        x.append(k*k)
    return x

@exe_time  # Decorator or wrapper function
def func_cube(n):  # The original Function
    y = []
    for k in n:
        y.append(k*k*k)
    return y

Now lets pass a list of values to the above functions :
lst = range(1, 100000)
op_square = func_square(lst)
# print('The squares of list of numbers is: ', op_square)

op_cube = func_cube(lst)
# print('The cubes of list of numbers is: ', op_cube)

# Result:
The execution time of func_square is: 22.13 milli sec.
The execution time of func_cube is: 46.87 milli sec.

#--------------------------------------------------------------Thanks--------------------------------------------------------------#

No comments:

Post a Comment

Hi User, Thank You for visiting My Blog. Please post your genuine Feedback or comments only related to this Blog Posts. Please do not post any Spam comments or Advertising kind of comments which will be Ignored.