Python decorators are generic and very powerful. You can find many examples of how they can be used at the decorator library of ( In this section, we will see how we can implement a memoization decorator ( 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 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__': ...

Get Advanced Python Programming now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.