Persistent variables in python

Duncan Booth duncan.booth at invalid.invalid
Wed Dec 27 04:11:33 EST 2006


"buffi" <bjorn.kempen at gmail.com> wrote:

> Is this concidered bad coding practice since I guess persistent
> variables in functions are not meant to be?
> 
There is a problem that this trick only works for functions and not for 
methods as it assumes that there is a global name through which you can 
access the function.

I think that more significantly is the question how you initialize the 
value (Lee Harr's decorator does that quite nicely though) or reset it, or 
have multiple instances each with their own saved value. As soon as you 
start asking those types of questions it is time to switch to using a 
class.

So in short, yes it is a plausible trick in some situations as a 
lightweight alternative to a class which has only static state and one 
method, but if you want a second method or multiple instances you'll want a 
real class. (And yes, I do realise that by embedding the function with 
state inside a factory function you can create multiple instances.)

Python also provides another lightweight way of saving state between calls. 
Consider whether your particular use can be written as a generator:

def dostuff():
    timesused = 0
    print "First call!"
    while 1:
        timesused += 1
        print "Function call", timesused
        yield timesused

>>> fn = dostuff()
>>> fn.next()
First call!
Function call 1
1
>>> fn.next()
Function call 2
2
>>> fn.next()
Function call 3
3
>>> timesused = fn.next()
Function call 4
>>> print timesused
4



More information about the Python-list mailing list