[SciPy-User] caching function values
Mon Mar 15 03:33:46 CDT 2010
I've attached another example which may do what you're after using a
decorator-based solution. The technique is called memoization and is
described in lectures 13 and 14 of the MIT OpenCourseWare intro to Comp.
Sci. and Programming course, which is now based on Python.
nicky van foreest wrote:
> Hi Ralf and Paul,
> Thanks for sharing your ideas.
> On 14 March 2010 04:21, Paul Anton Letnes <email@example.com> wrote:
>> On 13. mars 2010, at 13.06, nicky van foreest wrote:
>>> 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 = ):
>>> if firstTime == 1:
>>> A = 3 # typically some lengthy do-once computation to obtain a matrix A
>>> dummy.A = A # store it
>>> firstTime = 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.
>>> SciPy-User mailing list
>> 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.
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
More information about the SciPy-User