static keyword

Nick Jacobson nicksjacobson at yahoo.com
Thu Apr 29 10:07:39 EDT 2004


I believe the following "static" command would be useful in Python.

def foo():
    static i = [10, 11]
    static firstcall = True
    if firstcall:
        print "First pass"
        firstcall = False
    i[0] += 1
    print i[0]
foo()
foo()


This would output:

First pass
11
12

Just like in C, the variables i and firstcall are only assigned the
first time foo() is called.  To get this effect currently, one could
use default arguments or wrapping the whole thing in a class.  Both of
these solutions seem like hacks, the above method IMO is more
Pythonic. :)

I have a feeling this has been discussed before, but I can't find
anything on it.  Thanks,

--Nick



More information about the Python-list mailing list