Static Variables in Python?
Cliff Wells
cliff at develix.com
Mon Jul 31 16:02:17 EDT 2006
On Mon, 2006-07-31 at 15:21 -0400, Michael Yanowitz wrote:
> 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
> while (i < len(bits):
> print bits[i],
> print '\n'
Many people suggest that using a class for this is the Python idiom (and
perhaps it is), but I prefer to use a decorator for adding attributes to
functions in this case:
def attrs ( **kwds ):
''' taken from PEP 318 '''
def decorate ( f ):
for k in kwds:
setattr ( f, k, kwds [ k ] )
return f
return decorate
@attrs ( bits = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] )
def set_bit ( idx, val ):
set_bit.bits [ idx ] = int ( bool ( val ) )
print "Bit Array:"
for i in set_bit.bits:
print i,
print
>>> set_bit ( 4, 1 )
Bit Array:
0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0
>>> set_bit ( 5, 1 )
Bit Array:
0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0
Regards,
Cliff
More information about the Python-list
mailing list