Welcome, guest | Sign In | My Account | Store | Cart

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, 29 lines
 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!

2 comments

Louis RIVIERE 13 years, 4 months ago  # | flag

Nice ! It would be more Pythonic with :

if args not in func.cache:
Justin Shaw (author) 13 years, 4 months ago  # | flag

Thanks. I made the change.

Created by Justin Shaw on Sat, 19 Jul 2008 (MIT)
Python recipes (4591)
Justin Shaw's recipes (11)

Required Modules

Other Information and Tasks