ActiveState Code

Recipe 576365: Simple Cached Functions


This is a simplified version of George Sakkis recipe entitled "Cache decorator in python 2.4" (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/325205). In this version, no extra classes are required and this is small enough to implement on the fly.

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
def cachable(func):
    '''
    Cache results of function in func.cache.
    -- No keyword args allowed.
    '''
    func.cache = {}
    def out(*args):
        if args not in func.cache:
            func.cache[args] = func(*args)
        return func.cache[args]
    return out


# ------------------- test it out --------------------
@cachable
def fibonacci(n):
    if n == 0 or n == 1:
        out = 1
    else:
        out = fibonacci(n - 1) + fibonacci(n - 2)
    return out

import time
start = time.time()
for i in range(35):
    print i, fibonacci(i)
print 'Time:', time.time() - start

# 0.17 Seconds!

Comments

  1. 1. At 6:11 a.m. on 20 jul 2008, Louis Riviere said:

    Nice ! It would be more Pythonic with :

    if args not in func.cache:
    
  2. 2. At 12:58 p.m. on 20 jul 2008, Justin Shaw (the author) said:

    Thanks. I made the change.

Sign in to comment