A simple memcache memoizer for python>=2.2
Just a snippet of code because every once in a while I need something like the classic memoize decorator but am working on a CentOS 4 bix (with python 2.3!)
I am still testing it, and am not even sure it really works, but it should be close.
cache=memcache.Client(['127.0.0.1:11211'], debug=0) cachetimeout=30 def memoize(fun): def inner(*args, **kwargs): key=repr(fun)+repr(args)+repr(kwargs) cached = cache.get(key) if cached is None: val = fun(*args, **kwargs) print "Setting: ",key, "to: ",val cache.set(key,val,cachetimeout) return val return cached return inner
And later inside a class:
And that's it. The basic idea I stole from a blog who was inspired by a Paul Graham book. It can be trivially turned into a decorator, of course (but then only works on 2.4 and later).