regularpython@gmail.com
Decorators
A decorator is also a function, it takes another function as a parameter and adds some kinds of functionalities and returns function. We have a python function than why we use the decorator function. The decorator function is mainly used to control the functions and reduce the code (Reusable code). To get a better idea see the below
Example1:
''' Created on 23-Feb-2018 @author: sairam ''' import time def outerFunction(originalFunction): def innerFunction(*args, **kwargs): start = time.time() result = originalFunction(*args, **kwargs) print(f'execution time of {originalFunction.__name__} is {time.time()-start}') return result return innerFunction # a = outerFunction("hi") # a() @outerFunction def addition(a,b): return a+b @outerFunction def subtraction(a,b): return a-b print(addition(1, 3)) print(subtraction(2, 4))
Output:
execution time of addition is 0.0
4
execution time of subtraction is 0.0
-2
Example2:
''' Created on 16-Feb-2018 @author: sairam ''' import time def outerFuncion(originalFunction): def innerFunction(*args, **kwargs): statTime = time.time() originalFunction(*args, **kwargs) exectionTime = time.time() - statTime print(f"function name is {originalFunction.__name__} and exectionTime is {exectionTime}") return innerFunction #================================================================================= @outerFuncion def sum(): result = 0 for r in range(0,10000): result+=r return result sum() #================================================================================= @outerFuncion def multiplication(num): result = 0 for r in range(0,10000): result*=num return result multiplication(10) #================================================================================= @outerFuncion def division(num): result = 0 for r in range(0,10000): result/=num return result division(10)
Output:
function name is sum and exectionTime is 0.0029959678649902344
function name is multiplication and exectionTime is 0.001999378204345703
function name is division and exectionTime is 0.0019998550415039062
The use of Decorators:
Analytics, logging, and instrumentation
Validation and runtime checks
Creating frameworks
This avoids boiler-plate code.