Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > memoize again

Reply
Thread Tools

memoize again

 
 
yota.news@gmail.com
Guest
Posts: n/a
 
      11-21-2009
I spent a lot of time looking for tips on how to properly write
cache / memoize function.
Testing, merging and fixing contributed but half finished pieces of
code.
Here is the summary of what I learned through a clean example, might
it be useful for beginners.

#!/usr/bin/env python3.1 (should work in python 2.5)

def dcache(function) :
""" simple, dict based cache """
return memoize(function, cache={})

def ccache(cache = {}):
""" with dict-like custom cache. Can be any class with
at least __contains__, __setitem__ and __getitem__ methods """
def xcache(function):
return memoize(function, cache=cache)
return xcache

class memoize(object):
def __init__(self, function, cache):
self.function=function
self.cache=cache

def __get__(self, instance, cls=None):
self.instance = instance
return self

def __call__(self, *args):
if args not in self.cache:
self.cache[args] = self.function(self.instance, *args)
return self.cache[args]

which can be used as this:
- with the custom cache

@ccache(cache=customCache())
def compute(self, alpha, beta):
return alpha + beta

- or with a default dict() cache

@dcache
def compute(self, alpha, beta):
return alpha + beta

Each time compute() is called, the memoize decorator looks first into
the cache for a value whose key is the *args tuple.

The full content of the cache can be acessed as compute.cache.


~
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
efficient memoize decorator? thattommyhallll@gmail.com Python 11 08-19-2006 12:27 PM
AssertionError in pickle's memoize function Michael Hohn Python 3 10-31-2004 03:13 PM
RE: How to memoize functions? sismex01@hebmex.com Python 2 06-27-2003 05:25 PM
How to memoize functions? Chris Reedy Python 3 06-27-2003 02:18 PM
RE: How to memoize functions? sismex01@hebmex.com Python 0 06-26-2003 08:45 PM



Advertisments