Function decorator that caches function results

Diez B. Roggisch deets at nospam.web.de
Sun Oct 9 06:21:39 EDT 2005


>>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.

It's part of the closure - as well as fn, btw. So it is 
per-decorated-function.

Diez



More information about the Python-list mailing list