Pythonic way to do static local variables?
Mike Meyer
mwm at mired.org
Tue Apr 26 00:07:27 EDT 2005
Charles Krug <cdkrug at worldnet.att.net> writes:
> I've a function that needs to maintain an ordered sequence between
> calls.
>
> In C or C++, I'd declare the pointer (or collection object) static at
> the function scope.
>
> What's the Pythonic way to do this?
>
> Is there a better solution than putting the sequence at module scope?
I'm not sure what you mean by "an ordered sequence". Assuming that a
static counter variable will do the trick (i.e. - it's values will
sequence across calls), you can do this in a number of ways:
1) Use a class:
class counterClass:
def __init__(self):
self.count = 1
def __call__(self):
self.count = self.count + 1
counterFunc = counterClass()
2) Use an instance variable of the function:
def counterFunc():
foo.counter = foo.counter + 1
foo.counter = 1
You ought to be able to do this with closures as well, but I couldn't
seem to get that to work.
<mike
--
Mike Meyer <mwm at mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
More information about the Python-list
mailing list