CS 3723
 Programming Languages 
   Python Static Storage  


New Temporaries: Each time there is the result of an arithmetic operation in MIPS, we need a new temporary location to store this result. In C you could use a static variable, but Python doesn't have an exact analog, so the simplest way in Python is to use a global counter. [With complex expressions it would be difficult to be sure there was no interference unless each new temporary is distinct from the previous ones.]

For this purpose we need function that will keep incrementing a counter and returning the new incremented value. In C we can use a local static variable, but there isn't an exact analog in Python. You can use a global variable (simplest way), or one of the two techniques I found online. (There are other techniques involving classes that we'll get to later in the course -- um . . . not much time left.)

The method below uses a Python attribute, which is a value associated with an object. Attributes are very important, but for the purpose below we can use a user-defined attribute of a function:

Equivalent of static storage in Python: Use an attribute of a function
#include <stdio.h>

int next_int() {
   static int counter = 0;
   counter++;
   return counter;
}

int main() {
   int i;
   for (i = 0; i < 8; i++)
      printf("%i\n", next_int());
}

% cc -o static -Wall static.c ./static 1 2 3 4 5 6 7 8
# static.py: static counter in a function
import sys

def next_int(): # for temp variables
    next_int.count += 1
    return str(next_int.count)
next_int.count = -1 # define attribute

def my_incr(): # for temp variables
    if not hasattr(my_incr, "counter"): # !exist init
        my_incr.counter = 35*8 # define attribute
    my_incr.counter += 8
    return str(my_incr.counter)

for i in range(0,8):
    sys.stdout.write(next_int() + " ")
    sys.stdout.write(my_incr() + "\n")

% python static.py 0 288 1 296 2 304 3 312 4 320 5 328 6 336 7 344

( Revision date: 2014-09-28. Please use ISO 8601, the International Standard Date and Time Notation.)