Newbie: anything resembling static?

Phil Rittenhouse phil at dspfactory.com
Mon Feb 10 13:31:24 EST 2003


Erik Max Francis <max at alcyone.com> wrote in message news:<3E38960E.B7F85272 at alcyone.com>...
> anton wilson wrote:
> 
> > Is there any way of imitating "static" C function variables without
> > having to
> > define the variable as a global? I just want persistent function
> > variables
> > but i want them to be local to the function namespace. :S
> 
> Not explicitly.  You can use a global but prefix it with an underscore
> (a convention in Python that says "hands off").  

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

Under the covers Python would create a global for count but with a mangled
name, like _foo_count.  If it already exists from a previous call, it would
do nothing, so assignments would only happen once.

The only other change would be in the variable lookups.  As before Python
would search the local dictionary first, and then the global, but now
when it searches the global dictionary, it would first look for the mangled
name before looking for the unmangled name.

It's just sugar, but I think it looks cleaner.  Of course, as with any
such change, you'll break anyone's code that uses the name static.

Comments?
Phil 
-----------------
This email address will self-destruct in 30 days.




More information about the Python-list mailing list