Creating and Using Python Decorator

Creating and Using Python Decorator

Instructor-svgAl-Mamun Sarkar
Mar 26 , 2020

Creating and Using Python Decorator. The following code shows how to create and use a custom decorator in the Python programming language.

from time import time


def timer(any_function):
    def count_time():
        start = time()
        any_function()
        stop = time()
        print(stop-start, 'seconds')
        return
    return count_time


@timer
def hello():
    print('Hello World!')
    return


@timer
def another_function():
    for item in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
        print(item)
    return


hello()

another_function()

 

Output:

Hello World!
4.410743713378906e-05 seconds
1
2
3
4
5
6
7
8
9
10
4.6253204345703125e-05 seconds

 

  • Share On:
  • fb
  • twitter
  • pinterest
  • instagram