Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

decorators - trying to understand this simple example

Basically I'm trying to implement a timing decorator:

def laptime(func):
    def inner(*args):
        start = time.time()
        r = func(*args)
        print time.time()-start
    return r

@laptime
def loop(a,b):
    for i in range(a,b):
        print (i)

loop(2, 1000)

I tried many ways of making it work, but they all returns funny results that I don't understand... I know there are multiple other questions on the topic on SO, but somehow they weren't helpful for me to get a better grasp of how this should be done.

like image 512
jim jarnac Avatar asked Dec 29 '25 05:12

jim jarnac


1 Answers

A decorator function takes a function as an argument and returns a modified function. Your laptime doesn't return the modified function (inner), and it has the wrong indentation on return r.

Here's a repaired version. I've also changed it so it will run correctly on both Python 2 & Python 3.

import time

def laptime(func):
    def inner(*args):
        start = time.time()
        r = func(*args)
        print(time.time() - start)
        return r
    return inner

@laptime
def loop(a,b):
    for i in range(a,b):
        print(i)

loop(2, 10)

output

2
3
4
5
6
7
8
9
0.000479936599731

The @decorator syntax can be a bit mysterious at first, but you do get used to it eventually. :)

Doing

@laptime
def loop(a,b):
    for i in range(a,b):
        print(i)

is completely equivalent to this:

def loop(a,b):
    for i in range(a,b):
        print(i)

loop = laptime(loop)
like image 72
PM 2Ring Avatar answered Dec 30 '25 22:12

PM 2Ring



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!