Persistent variables in python

Steven D'Aprano steve at REMOVEME.cybersource.com.au
Wed Dec 27 22:10:56 EST 2006


On Wed, 27 Dec 2006 10:11:11 -0800, eduardo.padoan at gmail.com wrote:

> 
>> 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
>>
> 
> Ok, it is a matter of taste and I prefer the try/except way, but with
> hasattr you will do a function call and a intern 'truthness'
> verification each time you increment .timeUsed. With try/except, after
> the first time, you do nothing else than increment it.

That's not quite true. You do have to set up the try...except machinery,
but that's very cheap.

In any case, I didn't say that I like the hasattr idiom, merely that it is
available.



-- 
Steven D'Aprano 




More information about the Python-list mailing list