Home > Programming & scripting, Python > Fun with python. Persistent variables in functions

Fun with python. Persistent variables in functions

December 25th, 2006

Say that you want a function to keep track of the number of times you have called it. For this it would be easiest with some kind of persistent variable to increase each time the function is called.
This means that the first time you call the function, you need to set up that variable. All other calls should just increase it. There is a simple hack to do this

def doStuff():
  try:
    #Will throw exception if not set
    doStuff.timesUsed+=1

    ##
    #Insert stuff to do each time the function is called here
    ##
    print "Function call!"

  except AttributeError:
    doStuff.timesUsed = 0 # set up the variable

    ##
    #Put other stuff to call the first
    #time the function is called here
    ##
    print "First call!"

    doStuff() #recursive call. Will not throw exception now

Some output testing this:

>>> doStuff()
First call!
Function call!
>>> doStuff()
Function call!
>>> doStuff()
Function call!
>>> doStuff()
Function call!
>>> doStuff.timesUsed
4

buffi Programming & scripting, Python

  1. No comments yet.
  1. No trackbacks yet.