Posts

Showing posts with the label decorators

Print Execution Time Using Custom Decorator

  Code Example # Print Execution Time Using Custom Decorator  from datetime import datetime def print_time(fun):     def wrapper_method(*args, **kwargs):         start_time = datetime.now()         res = fun(*args, **kwargs)         end_time = datetime.now()         print("execution time : ", end_time-start_time)         print(res)     return wrapper_method @print_time def my_function1(goto=10):    # with params     for i in range(goto):         i = i**1000     return "200" @print_time def my_function2():           # without params     for i in range(10):         i = i**1000 my_function1(1000) my_fu...

Decorators in Python

Image
  Concept In Python, functions are the first class objects, which means that – Functions are objects; they can be referenced to, passed to a variable and returned from other functions as well. Functions can be defined inside another function and can also be passed as argument to another function. powerful and useful tool in Python since it allows programmers to modify the behavior of function or class. Decorators allow us to wrap another function in order to extend the behavior of wrapped function, without permanently modifying it. In Decorators, functions are taken as the argument into another function and then called inside the wrapper function. Code Example ''' Creating Decorator 1 ''' def uppercase_decorator(function):       def wrapper():             make_uppercase = function().upper()             return make_uppercase     re...