Newbie: anything resembling static?

Magnus Lie Hetland mlh at furu.idi.ntnu.no
Tue Feb 11 05:16:05 CET 2003


In article <4da3e801.0302101031.752f7121 at posting.google.com>, Phil
Rittenhouse wrote:
[snip]
>What I've been wondering lately is: could we add a 'static' keyword
>to the language to accomplish the same thing?
>
>You would use it in a way similar to the 'global' keyword, for example:
>
>def foo():
>   static count = 0
>   print count

This sort of local state is specifically what objects are for... I'd
rather advocate using them than adding a keyword for this...

However, if you want to simulate statics, default arguments are a
possibility:

def foo(count=[0]):
    print count[0]
    count[0] += 1

Default arguments are initialized when the functions are defined, and
may be manipulated subsequently (and are stored just like static
variables). Not very clean/elegant, IMO, but possible...

-- 
Magnus Lie Hetland               "Nothing shocks me. I'm a scientist." 
http://hetland.org                                   -- Indiana Jones




More information about the Python-list mailing list