[Tutor] (no subject)

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Sat Aug 28 02:00:29 CEST 2004

On Sat, 28 Aug 2004, Ashkan Aliabadi wrote:

> I'm back with a new question ;) This one seems simple. Today I just
> asked myself: How can I define a static variable in python?

Hi Ashkan,

Hmmm... Can you show us an example of what you mean by 'static'?  The word
is very overloaded.  If you can show us a code fragment from another
programming language, that'll help us to show the equivalent in Python.

For the moment, I'll guess that you mean 'static variable' in the context
of C functions.  In C, static variables are variables in a function that
stay alive between function calls.  For example, a program like:

/*** C Code***/
/*** Creates a newly allocated symbolic string.
     See: http://catb.org/~esr/jargon/html/G/gensym.html
#include <stdio.h>
#include <malloc.h>

/** don't forget to dealloc anything that comes from this! */
char* generateSymbol() {
  static int count = 0;
  char* nextSymbol = malloc(sizeof(char) * (5 + 1));
  sprintf(nextSymbol, "g%04d", count);
  return nextSymbol;

int main() {
  printf("%s\n", generateSymbol()); /* memory leak, I know... */
  printf("%s\n", generateSymbol());
  printf("%s\n", generateSymbol());
  printf("%s\n", generateSymbol());
  return 0;

This uses a static variable called 'count' that remembers its last value.
Conceptually, this generateSymbol() has a piece of persistant state.

It is possible to simulate this kind of static variable in Python, through
the use of a mutable default parameter.

def generateSymbol(_count=[0]):
    _count[0] += 1
    return "g%04d" % _count[0]

if __name__ == '__main__':
    print generateSymbol()
    print generateSymbol()
    print generateSymbol()
    print generateSymbol()

So that's one way to make a static variable.

However, this is slightly irregular as Python code.  Since this
generateSymbol() has state, it may be better modeled as an object:

class SymbolGenerator:
    def __init__(self, prefix):
        self.count = 0
        self.prefix = prefix

    def __call__(self):
        self.count += 1
        return "%s%04d" % (self.prefix, self.count)

generateSymbol = SymbolGenerator("g")

if __name__ == '__main__':
    print generateSymbol()
    print generateSymbol()
    print generateSymbol()
    print generateSymbol()

The example here shows that we can easily make callable objects that look
just like functions.  This is also a bit more flexible, since we can make
several specialized SymbolGenerators:

>>> anotherGenerator = SymbolGenerator("foo")
>>> anotherGenerator()
>>> anotherGenerator()
>>> anotherGenerator()

Good luck!

More information about the Tutor mailing list