Pythonic way to do static local variables?

Lonnie Princehouse finite.automaton at gmail.com
Tue Apr 26 16:58:23 EDT 2005


A quick, hackish way to keep a static variable is to declare it as a
parameter and give it a default value.  The parameter list is evaluated
when the function is compiled, not when it is called.   The underscores
are added as per convention to indicate that the variable is
special/private.

Example-

def cumulative_sum(arg, __static__ = []):
    __static__.append(arg)
    return reduce(lambda a,b: a + b, __static__)

#-------------------

>>> cumulative_sum(1)
1
>>> cumulative_sum(1)
2
>>> cumulative_sum(1)
3




More information about the Python-list mailing list