Function decorator that caches function results

Ron Adam rrr at
Sun Oct 9 16:26:53 CEST 2005

Steven D'Aprano wrote:
> On Sat, 08 Oct 2005 15:20:12 +0200, Lasse Vågsæther Karlsen wrote:
>>Ok, so I thought, how about creating a decorator that caches the 
>>function results and retrieves them from cache if possible, otherwise it 
>>calls the function and store the value in the cache for the next invokation.
>>This is what I came up with so far:
>>def cache_function(fn):
>>     cache = {}
>>     def cached_result(*args, **kwargs):
>>         if args in cache:
>>             return cache[args]
>>         result = fn(*args, **kwargs)
>>         cache[args] = result
>>         return result
>>     return cached_result
> I'm curious... where does cache live after you use cache_function to
> memoize some function? It doesn't appear to be an attribute of the newly
> memoized function, nor does it look like a global variable.

If I understand this correctly...

     if args in cache:

Creates a local binding to the "cache" object that gets returned with 
the cashed_result function the same as...

     result = fn(*args, **kwargs)

  ... the function 'fn' does here.  So they remain local bindings to 
objects in the scope they were first referenced from even after the 
function is returned.  In effect, 'cache' and 'fn' are replaced by the 
objects they reference before the cached_result function is returned.

Is this correct?


More information about the Python-list mailing list