Found out a quite fun way to store persistent variables in functions in
python.

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

    ##
    #Insert stuff to do each time the function is called here
    ##
    doStuff.timesUsed+=1
    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

------------


Is this concidered bad coding practice since I guess persistent
variables in functions are not meant to be?

/buffi (www.buffis.com)

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to