Persistent variables in python

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Tue Dec 26 19:06:49 EST 2006


On Tue, 26 Dec 2006 15:01:40 -0800, buffi wrote:


>> def doStuff(some, arguments, may, *be, **required):
>>      try:
>>          doStuff.timesUsed += 1
>>      except AttributeError:
>>          doStuff.timesUsed = 1
>>          # ... special case for first call ...
>>      # ...common code...
> 
> True, the recursivity is not needed there I guess :)
> 
> It just feels so ugly to use try/except to enable the variable but I've
> found it useful at least once.

That's a matter of taste. Try replacing the try...except block with
hasattr:

def doStuff():
    if hasattr(doStuff, timesUsed):
        doStuff.timesUsed += 1
    else:
        doStuff.timesUsed = 1
    do_common_code

Here is another alternative, using the fact that Python creates default
values for arguments once when the function is compiled, not each time it
is run:

def doStuff(some, *arguments, 
    # don't mess with the following private argument
    __private={'timesUsed': 0, 'otherData': 'Norwegian Blue'}):
    """ Do stuff with some arguments. Don't pass the __private 
    argument to the function unless you know what you are doing,
    it is for private use only. 
    """
    __private['timesUsed'] += 1
    do_common_code



-- 
Steven.




More information about the Python-list mailing list