Posts tagged ‘random ideas’
A python caching decorator for referential transparent functions
The following is quite a nice way of automating caching in python functions using decorators. This code will work whenever a function depends on only its paramters (this is called referential transparency.)
def cached(func): cache = {} def new_func(*args): if args in cache: return cache[args] else: temp = cache[args] = func(*args) return temp return new_func def non_cachedFunc(blah) ....blah @cached def cacheFunc(blah): ...blah
This makes turning caching on and off very easy and saves quite a lot of typing. The only overhead added to each call to a cached function should be one extra function call and a dictionary membership test.