Static variables

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Wed Jan 24 16:58:42 EST 2007


Neil Cerutti a écrit :
> On 2007-01-24, Florian Lindner <Florian.Lindner at xgm.de> wrote:
> 
>>does python have static variables? I mean function-local
>>variables that keep their state between invocations of the
>>function.
> 
> 
> Yup.  Here's a nice way. I don't how recent your Python must be
> to support this, though.
> 
> 
>>>>def foo(x):
> 
> ...   print foo.static_n, x
> ...   foo.static_n += 1
> ...
> 
>>>>foo.static_n = 0

Yup,I had forgotten this one. FWIW, it's an old trick.

There's also the closure solution:

def make_foo(start_at=0):
   static = [start_at]
   def foo(x):
     print static[0], x
     static[0] += 1
   return foo

foo = make_foo()

And this let you share state between functions:

def make_counter(start_at=0, step=1):
   count = [start_at]
   def inc():
     count[0] += step
     return count[0]
   def reset():
     count[0] = [start_at]
     return count[0]
   def peek():
     return count[0]

   return inc, reset, peek

foo, bar, baaz = make_counter(42, -1)
print baaz()
for x in range(5):
    print foo()
print bar()
print baaz()




More information about the Python-list mailing list