A python caching decorator for referential transparent functions

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

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.

Advertisements

Entry filed under: Uncategorized. Tags: , , , .

Fixing catastrophic mistakes with apt-get Currying, state and higher-order functions

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed


March 2008
M T W T F S S
« Feb   Apr »
 12
3456789
10111213141516
17181920212223
24252627282930
31  

%d bloggers like this: