Return to Snippet

Revision: 17564
at September 9, 2009 17:20 by manatlan


Initial Code
import cPickle,hashlib,tempfile,os,time,types

def cache(nbsec=0,path=None,islog=False):
    """ cache (decorator) tout retour de methode en pickable
        - nbsec : (opt) nb secondes du cache (si =0 unlimited)
        - path : (opt) chemin pour stocker le pickle (sinon temp dir)
        - islog: (opt) affiche un log clair des manips
    """
    def _f2(*args,**kwargs):
        mname = _f2.fct.__name__
        def log(msg): print "*** CACHE %s (%ds): " % (mname,nbsec),msg
        file=os.path.join(path or tempfile.gettempdir(),
            "zcache_%s_%s.pickle" % (mname,hashlib.md5(str(args)+str(kwargs)).hexdigest())
        )
        if os.path.isfile(file):
            if nbsec>0:
                ftime = os.stat(file).st_mtime
                ntime = time.time()
                isLoad = ftime + nbsec > ntime
                if isLoad:
                    if islog: log("use cache : %s renew in %ds" % (file,nbsec - (ntime - ftime)) )
                else:
                    if islog: log("cache has expired since %d sec" % (ntime - ftime))
            else:
                isLoad = True
                if islog: log("use cache : %s (no expiration time)" % (file,) )
            if isLoad:
                return cPickle.load(open(file,"rb"))
        else:
            if islog: log("no cache file")

        val = _f2.fct(*args, **kwargs)
        if islog: log("create %s"%file)
        fid=open(file,"wb")
        cPickle.dump(val,fid)
        fid.close()
        return val

    if type(nbsec) == types.FunctionType:   # to be able to work without decorator params
        _f2.fct, nbsec= nbsec , 0
        return _f2
    else:
        def _f1(func):
            _f2.fct = func
            return _f2
        return _f1

Initial URL


Initial Description


Initial Title
cache decorator

Initial Tags
python, cache

Initial Language
Python