importfunctoolsimporttimedeftimer(func):
"""Print the runtime of the decorated function"""@functools.wraps(func)defwrapper_timer(*args, **kwargs):
start_time=time.perf_counter() # 1value=func(*args, **kwargs)
end_time=time.perf_counter() # 2run_time=end_time-start_time# 3print(f"Finished {func.__name__!r} in {run_time:.4f} secs")
returnvaluereturnwrapper_timer@timerdefwaste_some_time(num_times):
for_inrange(num_times):
sum([i**2foriinrange(10000)])
Creating Singletons
importfunctoolsdefsingleton(cls):
"""Make a class a Singleton class (only one instance)"""@functools.wraps(cls)defwrapper_singleton(*args, **kwargs):
ifnotwrapper_singleton.instance:
wrapper_singleton.instance=cls(*args, **kwargs)
returnwrapper_singleton.instancewrapper_singleton.instance=Nonereturnwrapper_singleton@singletonclassTheOne:
pass