A Python function object has an attribute dictionary called func_dict
which is visible from outside the function and is mutable, but which is not modified when the function is called. (I learned this from answers to a question I asked yesterday (#1753232): thanks!) I was reading code (at http://pythonprogramming.jottit.com/functional%5Fprogramming) which memoized the computation of Fibonacci numbers and thought, "Why not use the func_dict
attribute for memoizing?" It worked (see below; the output's at the end of the code.). It's a little like having a class property available but having the initialization code outside the object (in this case, not a class but a function).
I wonder what similar (or dissimilar) tricks can be done using this attribute?
def fib(n):
if n in fib.cache:
print "found fib.cache[%d] = %d: " %(n, fib.cache[n])
return fib.cache[n]
else:
print "fib.cache[%d] = fib(%d) + fib(%d)" % (n, n-1, n-2)
fib.cache[n] = fib(n-1) + fib(n-2)
print "modified fib.cache: ", fib.cache
return fib.cache[n]
fib.cache = {0:0, 1:1}
for x in range(7):
print "==================>", x
print fib( x)
"""
==================> 0
found fib.cache[0] = 0:
0
==================> 1
found fib.cache[1] = 1:
1
==================> 2
fib.cache[2] = fib(1) + fib(0)
found fib.cache[1] = 1:
found fib.cache[0] = 0:
modified fib.cache: {0: 0, 1: 1, 2: 1}
1
==================> 3
fib.cache[3] = fib(2) + fib(1)
found fib.cache[2] = 1:
found fib.cache[1] = 1:
modified fib.cache: {0: 0, 1: 1, 2: 1, 3: 2}
2
==================> 4
fib.cache[4] = fib(3) + fib(2)
found fib.cache[3] = 2:
found fib.cache[2] = 1:
modified fib.cache: {0: 0, 1: 1, 2: 1, 3: 2, 4: 3}
3
==================> 5
fib.cache[5] = fib(4) + fib(3)
found fib.cache[4] = 3:
found fib.cache[3] = 2:
modified fib.cache: {0: 0, 1: 1, 2: 1, 3: 2, 4: 3, 5: 5}
5
==================> 6
fib.cache[6] = fib(5) + fib(4)
found fib.cache[5] = 5:
found fib.cache[4] = 3:
modified fib.cache: {0: 0, 1: 1, 2: 1, 3: 2, 4: 3, 5: 5, 6: 8}
8
"""