DEV Community

Harman Singh
Harman Singh

Posted on

Python Decorators

What are Python decorators

Python decorators is the text prefixed with a "@" above a function definition.

What does it look like in code

@calc_exec_time <-----
def sorting_algorithm():
    return [array.sort()][0]
Enter fullscreen mode Exit fullscreen mode

This Python Decorator will time how long it will take to execute the function called sorting_algorithm()

Creating a new decorator

Here is the base layout of a decorator:

def my_decorator(func):
    def wrapper():
        # decorator functionality goes here

    return wrapper
Enter fullscreen mode Exit fullscreen mode

Example decorator to calculate execution time

Here you will find a decorator function that will calculate execution time of a function

Decorator


import time

def calc_exec_time(func):
    """
    Calculates execution time of a function, by starting a counter before executing the function, and then stopping it after it has finished
    """

    def wrapper():
        t1 = time.time()
        func()
        t2 = time.time()
        duration = round(t2 - t1, 5)

        print(f'{func.__name__} took {duration} seconds')

    return wrapper
Enter fullscreen mode Exit fullscreen mode

Usage

@calc_exec_time
def sorting_algorithm():
    return [array.sort()][0]
Enter fullscreen mode Exit fullscreen mode

Of course your function may be longer than this one, but this is just an example.

Output

sorting_algorithm took 0.21101 seconds
Enter fullscreen mode Exit fullscreen mode

Top comments (0)