memoize again

Y

yota.news

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.


 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,128
Latest member
ElwoodPhil
Top