Python decorators

Example with a function decorator

Let's create a simple decorator that outputs the time necessary to run a code structure:

#!/usr/bin/env python3

import datetime


def timer(func):
    def wrapper():
        start = datetime.datetime.now()
        func()
        runtime = datetime.datetime.now() - start
        print("-- execution time:", runtime)
    return wrapper


@timer
def my_function():
    x = 0
    for i in range(200000000):
        x = i*2
    print(x)


my_function()

The result will be:

399999998
-- execution time: 0:00:13.640745

Example with a class decorator

#!/usr/bin/env python

import datetime

class Decorator:
    def __init__(self, func):
        self.func = func

    def __call__(self, *args, **kwargs):
        start = datetime.datetime.now()
        result = self.func(*args, **kwargs)
        runtime = datetime.datetime.now() - start
        print('-- Execution time:', runtime)
        return result


@Decorator
def my_function():
    x = 0
    for i in range(200000000):
        x = i * 2
    print(x)


my_function()

Result:

399999998
-- Execution time: 0:00:10.364860