-1

Total newbie herem trying to understand the flow of execution,, look at the following code:

from datetime import datetime
from time import *

def time_decorator(function,a=0):
    a +=1
    print(a)
    def wrapper(*args,**kwargs):
        t1= time()
        result = function(*args,**kwargs)
        t2 = time() - t1
        print("elapsed:", t2)
        return result
    a +=2
    print(a)
    return wrapper
@time_decorator
def add(x, y=10):
    sleep(2)
    return x + y

print (add(10))

The output is like this:

1
3
elapsed: 2.0001702308654785
20
1
3

my question is why the last vaues of 'a' are the same in the last 2 lines??, i was expectin to be increased by two more?...im not understanding the flow of excution of the interpreter, help!!

General Grievance
  • 4,555
  • 31
  • 31
  • 45
  • 2
    Um, are you sure that you gave the correct output? Because for me the output is different: Without the `print` function, it's `1` and `3`, and with the print function added, it's `elapsed: ...` and `20`, as expected. Also, decorators are tough; sure it's a good starting topic? – sammy Dec 01 '19 at 17:57
  • 1
    There is no second `1` and `3`; `a` is only used and printed when the decorator runs, when you define `add`. The flow is as follows: `add` is defined, then `time_decorator` is called with `add` as an argument and it returns a new function that calls `add`; this new function is bound to the name `add`. – chepner Dec 01 '19 at 18:02

1 Answers1

0

Decorators are just a fancy form of function application.

@time_decorator
def add(x, y=10):
    sleep(2)
    return x + y

is equivalent to

def add(x, y=10):
    sleep(2)
    return x + y

add = time_decorator(add)

The output involving the variable a only happens when time_decorator is called, not when you call the function add.

chepner
  • 497,756
  • 71
  • 530
  • 681