I have a question about function-based decorators. When I make the first call to sqrt(), I enter the decorator function, which I understand. However, every subsequent call to sqrt() only calls the temp_func, not the actual decorator again.
I thought decorators were called every time the method is called, but from the output it's obviously not happening. The temp function is being entered every time I call sqrt(), but not is_val_pos().
Could someone please elaborate on why this is happening? Thanks!
def is_val_pos(orig_func):
print 'Entering decorator'
def temp_func(val):
print 'Entering temp func'
if val < 0:
return 0
else:
return orig_func(val)
return temp_func
@is_val_pos
def sqrt(val):
print 'Entering sqrt method'
import math
return math.pow(val, (1.0/2))
print sqrt(-1)
print sqrt(4)
print sqrt(16)
Output:
Entering decorator
Entering temp func
0
Entering temp func
Entering sqrt method
2.0
Entering temp func
Entering sqrt method
4.0