view pylearn/dataset_ops/memo.py @ 998:8ba8b08e0442

added the image_patches dataset used in RanzatoHinton2010 modified mcRBM to use it.
author James Bergstra <bergstrj@iro.umontreal.ca>
date Tue, 24 Aug 2010 16:51:53 -0400
parents 5c7374bd127c
children c9ec065ff736
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.

    #TODO: use weak references instead of a normal dict so that the cache doesn't prevent
    #      garbage collection
    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
    return rval