Static vars in Python?

Remco Gerlich scarblac-spamtrap at pino.selwerd.nl
Sun May 7 15:47:56 EDT 2000


Juanjo Álvarez wrote in comp.lang.python:
> It's posible to have in Python static vars (that is, vars in a function 
> that retain his value over calls to the same function)?

Yes, in a way. By (ab)using mutable default arguments. 

Consider the following function that returns the sum of its argument and its
previous argument (or 0 the first time it's called):


def add(x, static_var = [0]):
   result = x+static_var[0]
   static_var[0] = x
   return result


>>> add(3)
3
>>> add(4)
7
>>> add(-1)
3
>>> add(1)
0

etc.

You should only use this once you understand what assignment really does in
Python, what a mutable object is, and how default parameters work exactly.

Before that, just use a global variable...

-- 
Remco Gerlich,  scarblac at pino.selwerd.nl
"This gubblick contains many nonsklarkish English flutzpahs, but the
 overall pluggandisp can be glorked from context"  (David Moser)



More information about the Python-list mailing list