Decorators - trying to understand this simple example

Basically I am trying to implement a time decoder:

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've tried many ways to make it work, but they all return funny results that I don't understand ... I know there are many other related questions on SO, but somehow they didn't help me better understand how it should be done.

+3


source to share


1 answer


The decorator function takes a function as an argument and returns the modified function. Yours laptime

does not return the modified function ( inner

) and is indented incorrectly by return r

.

Here's the fixed version. I also changed it to work correctly in both Python 2 and 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 syntax @decorator

may be a little cryptic at first, but you eventually get used to it. :)

Performance

@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)

      

+6


source







All Articles