Package: decoratorutilities
DecoratorUtilitiesReadthedocs ReferencePlease read our documentation here:Readthedocs ReferencePackage ReferenceOur package reference link is:https://pypi.org/project/decoratorutilitiesMenuIntroInstallationDecoratorsCheck Type DecoratorOverloading DecoratorMocking DecoratorMemoized DecoratorTimeit DecoratorSingleton DecoratorIntroDecoratorUtilities is a python library that provides different utilities for functions and class methods such as
to check parameters and return type, allow overloading, to cache results to speed up them, instantiate a Singleton object
and mocking at runtimeInstallationpipinstalldecoratorutilitiesDecoratorsCheck Type DecoratorDecorate your own functions with@checktypedecorator to check parameters type and return type tooExample:fromdecoratorutilitiesimportchecktypeimportpytest@checktypedefmy_functon(a:int,b:int)->int:return1# Valid usage: Integer parameters and return typemy_functon(5,6)# return 1assertmy_functon(5,6)==1# True# Invalid usage: String parameters and return typewithpytest.raises(TypeError):my_functon("5","6")# Raises TypeError Exceptionwithpytest.raises(TypeError):my_functon("invalid",b="Invalid")# Raises TypeError Exceptionwithpytest.raises(TypeError):my_functon(a="invalid",b="Invalid")# Raises TypeError Exceptionwithpytest.raises(TypeError):assertmy_functon(5,6)=="1"# Raises TypeError ExceptionDecorate your own class methods with@checktypedecorator to check parameters type and return type tooExample:fromdecoratorutilitiesimportchecktypeimportpytestclassX(object):@checktype# checktype decorator for classes methodsdefmy_function(self,value:int):returnvalue# Valid usage: Integer parameters and return typeassertX().my_function(1)==1# True# Invalid usage: String parameters and return typewithpytest.raises(TypeError):X().my_function('1')# Raises TypeError Exceptionwithpytest.raises(TypeError):X().my_function(1)=="1"# Raises TypeError ExceptionOverloading DecoratorDecorate your own function with@overloaddecorator to define multiple functions with same name but with different parametersExample:fromdecoratorutilitiesimportoverload@overloaddefmy_functon(a:int):return1@overloaddefmy_functon(a:str):return2# Invoke first my_functon and return 1my_functon(1)# Invoke second my_functon and return 2my_functon('1')Decorate your own class method with@overloaddecorator to define multiple class methods with same name but with different parametersExample:fromdecoratorutilitiesimportoverloadclassX(object):@overloaddefx(self,x:int):returnint@overloaddefx(self,x:str):returnstrassertX().x(1)==int# TrueassertX().x('1')==str# TrueMocking DecoratorDecorate your own function with@mockingdecorator to mock that function adding args in a tuple, kwargs in a dict and return valueExample:fromdecoratorutilitiesimportmocking# Define args tuple, kwargs dict and return value@mocking([((1,2,3),{"a":1},1),((4,5,6),{"b":2},2)])defa():pass# Valid usageasserta(1,2,3,a=1)==1# return 1asserta(4,5,6,b=2)==2# return 2# Invalid usageasserta(7,8,9,c=1)==1# Raises KeyError ExceptionMemoized DecoratorDecorate your own function or class method with@memoizeddecorator to speed up it by storing the results and returning the cached result when the same inputs occur againExample:fromdecoratorutilitiesimportmemoizedimportdatetimedefutil_run_function_with_time(fn,args,kwargs):start_time=datetime.datetime.now()tmp=fn(*args,**kwargs)end_time=datetime.datetime.now()return(end_time-start_time),tmp@memoizeddefmemoized_fibonacci(x):ifx==0:return0ifx==1:return1returnmemoized_fibonacci(x-1)+memoized_fibonacci(x-2)deffibonacci(x):ifx==0:return0ifx==1:return1returnfibonacci(x-1)+fibonacci(x-2)fib_value=20memoized_execution_time,memoized_value=util_run_function_with_time(memoized_fibonacci,(fib_value,),{})# Return execution time and value for memoized functionunmemoized_execution_time,unmemoized_value=util_run_function_with_time(fibonacci,(fib_value,),{})# Return execution time and value for unmemoized functionprint(f"memoized_execution_time:{memoized_execution_time}- unmemoized_execution_time:{unmemoized_execution_time}")assertmemoized_execution_time<unmemoized_execution_time# OKassertmemoized_value==unmemoized_value# OKTimeit DecoratorDecorate your own function with@timeitdecorator to monitoring execution timeExample:fromdecoratorutilitiesimporttimeitimporttime@timeitdefhello():time.sleep(0.1)if__name__=="__main__":hello()# print "Execution time: 100.75 ms"Debug DecoratorDecorate your own function with@debugdecorator to print in console more Exception detailsExample:fromdecoratorutilitiesimportdebugimportpytest@debugdefa():message="Hello "+5returnmessagewithpytest.raises(TypeError):a()# Print in console: Found "<class 'TypeError'>" Exception in file "('../tests', 'test_debug.py')" on line "9"# Error message: "can only concatenate str (not "int") to str"Decorate your own class methods with@debugdecorator to print in console more Exception detailsExample:fromdecoratorutilitiesimportdebugimportpytestclassA(object):@debugdef__init__(self):self.message="Hello "+5withpytest.raises(TypeError):A()# Raises TypeError ExceptionSingleton DecoratorDecorate your own classes with@singleton()decorator to ensure that only one instance of the singleton class ever exists.
Never invoke@singleton()decorator without brackets otherwise it will cause problems
Define your class method__init__()without parameters, pass them to the@singleton()decoratorExample with args and kwargsimportpytestfromdecoratorutilitiesimportsingleton@singleton(10,message="Message to send",email=["simone.scalamandre95@gmail.com"])classA(object):def__init__(self):self.x=50# Define constant class attributedefprint_hello(self):# Custom methodreturn"Hello World"# Valid usageassertA[0]==10# True -> Get first argassertA.x==50# True -> Get decorated class attributeassertA.print_hello()=="Hello World"# True -> Get decorated class method "print_hello()"assertA.message=="Message to send"# True -> Get kwarg "message" passed to Singleton decoratorassertA.email==["simone.scalamandre95@gmail.com"]# Truewithpytest.raises(TypeError):# Invalid usage, brackets are missing@singletonclassB(object):def__init__(self):self.x=10B()# Raises TypeError ExceptionWe can define our singleton class with or without args and kwargs parameters but we can only instantiate oneExampleimportpytestfromdecoratorutilitiesimportsingleton@singleton()classA(object):def__init__(self):pass@singleton(x=10)classB(object):def__init__(self):passwithpytest.raises(TypeError)ase:A()# Raises TypeError Exceptionwithpytest.raises(TypeError):B()# Raises TypeError Exception