[SciPy-User] caching function values
Paul Anton Letnes
paul.anton.letnes at gmail.com
Sat Mar 13 22:21:50 EST 2010
On 13. mars 2010, at 13.06, nicky van foreest 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
>
> 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
> _______________________________________________
> SciPy-User mailing list
> SciPy-User at scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user
How about just making the following class?
class DummyClass(object):
def __init__():
self.A = lengthy_calculation()
def __call__(self, x):
return self.A *x
Somewhere else, type
dummy = DummyClass()
y = dummy(x) # or whatever
I'd say that this is as readable, and in fact, not noticeably longer.
Paul
More information about the SciPy-User
mailing list