Function decorator that caches function results

Lasse Vågsæther Karlsen lasse at vkarlsen.no
Sat Oct 8 11:10:48 EDT 2005


Sam Pointon wrote:
> What about not storing args at all? Something like this:
> 
> def cache_function(func, args_list):
>     cache = {}
>     def cached_result(*args, **kwargs):
>         kwargs.update(dict(zip(args_list, args)))
>         if kwargs in cache:
>             return cache[kwargs]
>         result = func(**kwargs)
>         cache[kwargs] = result
>         return result
>     return cached_result
> 
> args_list is a list of all the argument names, so that they can be
> converted into keyword arguments.
> 

I'll take a look at the zip function, didn't know about that one, but 
your example also has the problem that dictionaries can't be used as 
dictionary keys, but that can be easily solved. I think I can simplify 
my solution with some of yours.

The parameter names can be gotten by doing a inspect.getargspec(fn)[0] 
so that can be done by the decorator function.

-- 
Lasse Vågsæther Karlsen
http://usinglvkblog.blogspot.com/
mailto:lasse at vkarlsen.no
PGP KeyID: 0x2A42A1C2



More information about the Python-list mailing list