Pythonic way to do static local variables?
Bengt Richter
bokr at oz.net
Wed Apr 27 02:01:29 EDT 2005
On 26 Apr 2005 13:58:23 -0700, "Lonnie Princehouse" <finite.automaton at gmail.com> wrote:
>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
>
This default-value hack is what my presets decorator was motivated to replace
(if you are willing to depend to a byte-code-hacking decorator ;-)
Regards,
Bengt Richter
More information about the Python-list
mailing list