[SciPy-User] caching function values
nicky van foreest
vanforeest at gmail.com
Mon Mar 15 04:12:02 EDT 2010
Hi Ralf and Paul,
Thanks for sharing your ideas.
Nicky
On 14 March 2010 04:21, Paul Anton Letnes <paul.anton.letnes at gmail.com> wrote:
> 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
> _______________________________________________
> SciPy-User mailing list
> SciPy-User at scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user
>
More information about the SciPy-User
mailing list