Python decorators are generic and very powerful. You can find many examples of how they can be used at the decorator library of python.org (j.mp/pydeclib). In this section, we will see how we can implement a memoization decorator (j.mp/memoi). All recursive functions can benefit from memoization, so let's try a function number_sum() that returns the sum of the first n numbers. Note that this function is already available in the math module as fsum(), but let's pretend it is not.
First, let's look at the naive implementation (the number_sum_naive.py file):
def number_sum(n):
'''Returns the sum of the first n numbers'''
assert(n >= 0), 'n must be >= 0'
if n == 0:
return 0
else:
return n + number_sum(n-1)
if __name__ == '__main__':
from timeit import Timer...