On 9/30/07, David Seruyange <[EMAIL PROTECTED]> wrote: > I'm wondering how one caches things in python in a manner similar to how a > static variable or class member might in C#. I can only think of an > equivalent in something like a global variable, but is there another? I'm > not good enough yet to think in a manner "pythonic" but I've an inkling that > a generator may do this?
There are a couple of ways to do this. First (my favourite), a class with a "__call__" method can be used as a function: >>> class Func: ... def __init__(self): ... self.static = 0 ... def __call__(self, i): .... self.static += 1 .... print "called", self.static, "times" .... return i*2 .... >>> f = Func() >>> f(1) called 1 times 2 >>> f(3) called 2 times 6 Another trick is that functions are objects themselves, and you can add attributes to them. (The drawback here is that you need to initialize the static outside the function, otherwise you'll get an exception. Also, I find it really ugly to use the function's name inside the function itself.) >>> def func(i): ... func.static += 1 ... print "called", func.static, "times" ... return i*2 ... >>> func.static = 0 >>> func(1) called 1 times 2 >>> func(3) called 2 times 6 Another trick that's sometimes recommended, which I find really ugly, is to use a list as a hidden default parameter. The same list will be used for each call, so you can put items that you want to save between calls into it. Of course, if the user calls the function with their own list all the "static" parameters get messed up, which is why I don't like this solution. >>> def func(i, static = [0]): ... static[0] += 1 ... print "called", static[0], "times" ... return i*2 ... >>> func(1) called 1 times 2 >>> func(3) called 2 times 6 For your specific requirement, though... > This program (where I want to cache a list of > factorials once computed) is what prompted my questions: This is known as "memoization". Google for "python memoize" to get some good (if complex) recipes to take care of this. Joe _______________________________________________ Users mailing list Users@lists.ironpython.com http://lists.ironpython.com/listinfo.cgi/users-ironpython.com