Posts tagged ‘code samples’

A python caching decorator for referential transparent functions

The following is quite a nice way of automating caching in python functions using decorators. This code will work whenever a function depends on only its paramters (this is called referential transparency.)

def cached(func):
    cache = {}
    def new_func(*args):
        if args in cache:
             return cache[args]
        else:
             temp = cache[args] = func(*args)
             return temp
    return new_func

def non_cachedFunc(blah)
    ....blah

@cached
def cacheFunc(blah):
    ...blah

This makes turning caching on and off very easy and saves quite a lot of typing. The only overhead added to each call to a cached function should be one extra function call and a dictionary membership test.

March 12, 2008 at 9:42 pm Leave a comment


June 2017
M T W T F S S
« Nov    
 1234
567891011
12131415161718
19202122232425
2627282930