Ir al contenido principal

Ralsina.Me — El sitio web de Roberto Alsina

A simple memcache memoizer for python>=2.2

Just a snip­pet of code be­cause ev­ery once in a while I need some­thing like the clas­sic mem­o­ize dec­o­ra­tor but am work­ing on a Cen­tOS 4 bix (with python 2.3!)

I am still test­ing it, and am not even sure it re­al­ly work­s, 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 lat­er in­side a class:

def myfun(self,arg):
   :
   :
myfun=memoize(myfun)

And that's it. The ba­sic idea I stole from a blog who was in­spired by a Paul Gra­ham book. It can be triv­ial­ly turned in­to a dec­o­ra­tor, of course (but then on­ly works on 2.4 and lat­er).


Contents © 2000-2024 Roberto Alsina