Static variables

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Wed Jan 24 16:31:29 EST 2007


On Wed, 24 Jan 2007 21:48:38 +0100, Florian Lindner wrote:

> Hello,
> does python have static variables? I mean function-local variables that keep
> their state between invocations of the function.

There are two ways of doing that (that I know of).

The simplest method is by having a mutable default argument. Here's an
example:

def foo(x, _history=[]):
    print _history, x
    _history.append(x)

>>> foo(2)
[] 2
>>> foo(3)
[2] 3
>>> foo(5)
[2, 3] 5


Another method is to add an attribute to the function after you've created
it:

def foo(x):
    print foo.last, x
    foo.last = x

foo.last = None


>>> foo(3)
None 3
>>> foo(6)
3 6
>>> foo(2)
6 2


But the most powerful method is using generators, which remember their
entire internal state between calls. Here's a simple example, one that
returns the integers 0, 1, 3, 6, 10, ...  

def number_series():
    increment = 1
    n = 0
    while True:
        yield n  # instead of return
        n += increment
        increment += 1


Notice that in this case there is no exit to the function: it loops
forever because the series goes on for ever. If you want to exit the
generator, just use a plain return statement (don't return anything), or
just exit the loop and fall off the end of the function.

This is how we might use it:

Create an iterator object from the generator function, and print the first
six values:

>>> gen = number_series()
>>> for i in range(6): print gen.next()
...
0
1
3
6
10
15

Sum the values from the current point up to 100:

>>> s = 0
>>> n = gen.next()
>>> n
21
>>> for x in gen:
...     if x >= 100:
...             break
...     n += x
...
>>> n
420

Reset the iterator to the start:

>>> gen = number_series()

For generators that terminate, you can get all the values in one go with
this:

everything = list(gen)  # or everything = list(number_series())

but don't try this on my example, because it doesn't terminate!


-- 
Steven.




More information about the Python-list mailing list