[SciPy-User] caching function values
nicky van foreest
vanforeest at gmail.com
Sat Mar 13 16:06:10 EST 2010
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
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.)
Thanks for any advice.
Nicky
More information about the SciPy-User
mailing list