Newbie: anything resembling static?

Alex Martelli aleax at aleax.it
Wed Jan 29 16:56:21 EST 2003


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

There are several ways you can approximate this effect, e.g.:

def one(fakedefault=[]):
    fakedefault.append('x')
    return ''.join(fakedefault)

def two():
    try: two.staticvar.append('x')
    except AttributeError: two.staticvar = ['x']
    return ''.join(two.staticvar)

def three():
    staticvar = []
    def innerthree():
        staticvar.append('x')
        return ''.join(staticvar)
    global three
    three = innerthree
    return innerthree()

def four():
    four.staticvar.append('x')
    return ''.join(four.staticvar)
four.staticvar = []

def five():
    staticvar = []
    def innerfive():
        staticvar.append('x')
        return ''.join(staticvar)
    return innerfive
five = five()


simplest, of course, is to drop the arbitrary "local to the function
namespace" prerequisite in favour of a global with a suitable
name convention:

_six_staticvar = []
def six():
    _six_staticvar.append('x')
    return ''.join(_six_staticvar)


Anyway, all of these functions are to be called without arguments,
and each call returns a string of one more 'x' than the previous
one via different approximations to a "function static var".


Alex





More information about the Python-list mailing list