static keyword

Georgy no.mail at available.net
Thu Apr 29 11:26:07 EDT 2004


"Nick Jacobson" <nicksjacobson at yahoo.com> wrote in message news:f8097096.0404290607.78aa9ce3 at posting.google.com...
| 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. :)

"Pythonic" way is to use the oddity of default arguments:

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

--
Georgy





More information about the Python-list mailing list