# [SciPy-User] caching function values

Gary Ruben gruben@bigpond.net...
Mon Mar 15 03:33:46 CDT 2010

```Hi Nicky,

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.

Gary R.

nicky van foreest wrote:
> Hi Ralf and Paul,
>
> Thanks for sharing your ideas.
>
> Nicky
>
> On 14 March 2010 04:21, Paul Anton Letnes <paul.anton.letnes@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.)
>>>
>>>
>>> Nicky
>>> _______________________________________________
>>> SciPy-User mailing list
>>> SciPy-User@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

-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: memoization_example.py
Url: http://mail.scipy.org/pipermail/scipy-user/attachments/20100315/c4c18f5b/attachment.pl
```