Function decorator that caches function results

Duncan Booth duncan.booth at invalid.invalid
Sat Oct 8 09:53:28 EDT 2005


Lasse Vågsæther Karlsen wrote:
> However, this:
> 
> for index in range(1, 101):
>      print index, fibonacci(idx = index)
> 
> this one uses the kwargs list of arguments, and I'm not sure how to 
> change my function to take that into account.
> 
> Does anyone have any clues as to how to do that?
> 
> The solution would have to consider fibonacci(50) and fibonacci(idx = 
> 50) as the same call and thus retrieve the second one from the cache.
> 

Most of your gain comes from caching the recursive calls, not from caching 
the original call.

If the solution doesn't consider keyword arguments equivalent to positional 
arguments, it will make *one* call to the real function, and then the 
recursive call will still come out of the cache, so the net result will 
still be to give you almost all the speedup you wanted. 

Unless the results stored in the cache are very large data structures, I 
would suggest that you simply store (args,kwargs) as the cache key and 
accept the hit that sometime you'll cache the same call multiple times.



More information about the Python-list mailing list