Newbie: anything resembling static?

Alex Martelli aleax at
Wed Jan 29 22:56:21 CET 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=[]):
    return ''.join(fakedefault)

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

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

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

def five():
    staticvar = []
    def innerfive():
        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():
    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".


More information about the Python-list mailing list