Static variables

Neil Cerutti horpner at yahoo.com
Wed Jan 24 16:08:27 EST 2007


On 2007-01-24, Florian Lindner <Florian.Lindner at xgm.de> wrote:
> does python have static variables? I mean function-local
> variables that keep their state between invocations of the
> function.

Yup.  Here's a nice way. I don't how recent your Python must be
to support this, though.

>>> def foo(x):
...   print foo.static_n, x
...   foo.static_n += 1
...
>>> foo.static_n = 0
>>> for i in range(5):
...   foo("?")
...
0 ?
1 ?
2 ?
3 ?
4 ?

If you need to use an earlier version, then a "boxed" value
stored as a keyword parameter will also work.

>>> def foo(x, s=[0]):
...   print s[0], x
...   s[0] += 1
...
>>> for i in range(5):
...   foo("!")
...
0 !
1 !
2 !
3 !
4 !

The latter is not as nice, since your "static" variable is easy
to clobber by passing something into the function.

-- 
Neil Cerutti



More information about the Python-list mailing list