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.


~°
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to