view pylearn/dataset_ops/memo.py @ 1531:88f361283a19 tip

Fix url/name to pylearn2.
author Frederic Bastien <nouiz@nouiz.org>
date Mon, 09 Sep 2013 10:08:05 -0400
parents c9ec065ff736
children
line wrap: on
line source

"""Provide a decorator that caches expensive functions
"""
import logging
_logger = logging.getLogger(__file__)
info = _logger.info
def infop(*args):
    info(' '.join(str(a) for a in args))

def memo(f):
    #TODO: support kwargs to rval.  This requires looking up the names of f's parameters to 
    #      construct a proper key.
    cache = {}
    def rval(*args):
        if args not in cache:
            cache[args] = f(*args)
        return cache[args]
    def forget():
        for k in cache.keys():
            del cache[k]
    rval.cache = cache
    rval.forget = forget
    rval.__name__ = 'memo@%s'%f.__name__
    rval.cache = cache
    rval.__doc__ = f.__doc__
    return rval