I want to count the number of times a given function has been called.
So, I made a countcalls
decorator to give my functions a __callcount
attribute which gets incremented on each call. Simple enough.
My issue is getting the __callcount
value back out later.
Here's my code:
import functools
def countcalls(f):
f.__callcount = 0
@functools.wraps(f)
def _countcalls(*args, **kwds):
f.__callcount += 1
print(' Called {0} time(s).'.format(f.__callcount))
return f(*args, **kwds)
return _countcalls
@countcalls
def fib(n):
if n < 0:
raise ValueError('n must be > 0')
if n == 0 or n == 1:
return 1
return fib(n-1) + fib(n-2)
if __name__ == '__main__':
print('Calling fib(3)...')
x = fib(3)
print('fib(3) = {0}'.format(x))
print('Calling fib(3) again...')
x = fib(3)
print('fib(3) = {0}'.format(x))
print('fib was called a total of {0} time(s).'.format(fib.__callcount))
Which generates the following output (Python v3.3.0):
Calling fib(3)...
Called 1 time(s).
Called 2 time(s).
Called 3 time(s).
Called 4 time(s).
Called 5 time(s).
fib(3) = 3
Calling fib(3) again...
Called 6 time(s).
Called 7 time(s).
Called 8 time(s).
Called 9 time(s).
Called 10 time(s).
fib(3) = 3
fib was called a total of 0 time(s).
Why does fib.__callcount
equal 0
on the last line? As the output shows, __callcount
gets incremented, and persists between calls of fib
.
What am I missing?