Static Variables in Python?

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Mon Jul 31 16:42:34 EDT 2006


Michael Yanowitz a écrit :
>   Is it possible to have a static variable in Python - 
> a local variable in a function that retains its value.
> 
>  For example, suppose I have:
> 
> def set_bit (bit_index, bit_value):
>    static bits = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
>    bits [bit_index] = bit_value
> 
>    print "\tBit Array:"
>    int i

Syntax error

>    while (i < len(bits):
>       print bits[i],

Nice infinite loop...

Python's canonical way to iterate over a sequence is the for loop:
for bit in bits:
   print bit,

And FWIW, for what you want to do, you don't even need a loop:
print "\n".join(map(str, bits))

>    print '\n'


>  
>    I realize this can be implemented by making bits global, but can
> this be done by making it private only internal to set_bit()?  I don't
> want bits to be reinitialized each time. It must retain the set values
> for the next time it is called.

While there are some more or less hackish solutions (cf Roel answers and 
my answers to it), the usual way to have functions maintaining state is 
to define a class and instanciate it. Note that Python's functions are 
objects, and that it's possible to write your own callable objects too 
if you really want a function call syntax:

class Setbit(object):
   def __init__(self):
     self._bits = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
   def call(self, index, value):
     self._bits[index] = value
   def values(self):
     return self._bits[:]

set_bit = Setbit()
set_bit(1, 1)
print "".join(map(str, set_bit.values()))




More information about the Python-list mailing list