[SciPy-User] caching function values

Ralf Gommers ralf.gommers at googlemail.com
Sat Mar 13 22:15:08 EST 2010


On Sun, Mar 14, 2010 at 5:06 AM, nicky van foreest <vanforeest at gmail.com>wrote:

> Hi,
>
> When calling a function for the first time I like to cache some
> complicated computations (that only have to be done once), and then
> use this cached stuff in all subsequent calls to the functions. I came
> across the following trick on the net:
>
> def dummy(x, firstTime = [1]):
>    if firstTime[0] == 1:
>        A = 3  # typically some lengthy do-once computation to obtain a
> matrix A
>        dummy.A = A # store it
>        firstTime[0] = 0 # ensure this piece of code will not be run again
>    u = dummy.A*x  # use the cached value of A in the real computations
>    return u
>
> The above is not too complicated, but what's ugly is the firstTime keyword
in the signature. This looks better to me:
def dummy(x):
   if not hasattr(dummy, '_firsttime'):
       A = 3  # typically some lengthy do-once computation to obtain a
matrix A
       dummy.A = A # store it
   u = dummy.A*x  # use the cached value of A in the real computations
   dummy._firsttime = False
   return u


> Are there other (less tricky) ways to achieve the same effect, without
> using a class? (As far as I can see, using classes would involve some
> extra lines of code, for instance, I have to instantiate it.)
>

As long as the code is readable, why not use a few more lines? If your
calculation of A only has to run once, it doesn't really belong inside the
function. Either use a class, or (even easier) a private object outside the
function to store the result of the computation.

Cheers,
Ralf
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.scipy.org/pipermail/scipy-user/attachments/20100314/fcf3280a/attachment.html>


More information about the SciPy-User mailing list