You can use my simple solution to the problem. It is really straightforward, nothing fancy:
class MemCache(dict):
def __init__(self, fn):
dict.__init__(self)
self.__fn = fn
def __getitem__(self, item):
if item not in self:
dict.__setitem__(self, item, self.__fn(item))
return dict.__getitem__(self, item)
mc = MemCache(lambda x: x*x)
for x in xrange(10):
print mc[x]
for x in xrange(10):
print mc[x]
It indeed lacks expiration funcionality, but you can easily extend it with specifying a particular rule in MemCache c-tor.
Hope code is enough self-explanatory, but if not, just to mention, that cache is being passed a translation function as one of its c-tor params. It's used in turn to generate cached output regarding the input.
Hope it helps