Decorator Functions in Python 3

#!/usr/bin/python3 ''' Decorator function is a function that also use another function to perform by using @name_of_the_function above the function that we want to call This is an example: I created elapsed_time(f) to calculate big_sum() with "@elapsed_time" above big_sum() I just need to call big_sum() in main() to execute big_sum() that going to be passed to elapsed_time(f) and will give the result of sum and the time that python needed to performed the calculation Output: Big sum is 49995000 Execution time: 15.625 ms ''' import time def elapsed_time(f): def wrapper(): start = time.process_time() f() end = time.process_time() print(f'Execution time: {(end - start):.2f} ms') return wrapper @elapsed_time def big_sum(): num_list = [] for num in range(0, 10000): num_list.append(num) print(f'Big sum is {sum(num_list)}') def main(): big_sum() if __name__ == '__main__': main()
Decorator function is a function that use another function by using "@name_of_the_function" above another function (that we want to call)

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.