Static Variables in Python?

Paddy paddy3118 at netscape.net
Mon Jul 31 17:00:04 EDT 2006


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'
>
>
>    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.
>
>
> Thanks in advance:
> Michael Yanowitz

You can do things with function attributes

def foo(x):
  foo.static += x
  return foo.static
foo.static = 0

If you are going to set function attributes a lot, then you might like
to addd an attriute setter decorator to your toolbox:

def attributeSetter( **kw):
    " decorator creator: initialises function attributes"
    def func2(func):
        " decorator: initialises function attributes"
        func.__dict__.update(kw)
        return func
    return func2

def accumulator(n):
    """ return an accumulator function that starts at n
    >>> x3 = accumulator(3)
    >>> x3.acc
    3
    >>> x3(4)
    7
    >>> x3.acc
    7
    """
    @attributeSetter(acc = n)
    def accum(i):
        accum.acc+= i
        return accum.acc
    return accum


- Paddy




More information about the Python-list mailing list