modifying static (local) method variables
t scytale
scytale at gmail.com
Fri Nov 12 11:37:35 EST 2004
i am using a mutable default paramater to simulate a static method variable.
i notice that
- assigning to the var inside the method causes it to return to the
default value at each call.
- appending to the var gives the expected behaviour (the value is
preserved to the next call
why is this?
def GetCachedVal(val=[]):
print 'start val:', val
if val:
return val
print 'initializing'
val = TimeConsumingSetup() # assignment
return val
>> GetCachedVal()
start val: []
initializing
>> print val
[<eDatabase instance at 0x87>, <eHandle instance at 0x8755e>]
>>GetCachedVal()
start val: []
initializing
>>print val
[<eDatabase instance at 0x87>, <eHandle instance at 0x8755e>]
def GetCachedVal(val=[]):
print 'start val:', val
if val:
return val
print 'initializing'
val += TimeConsumingSetup() # append
return val
>> GetCachedVal()
start val: []
initializing
>> print val
[<eDatabase instance at 0x87>, <eHandle instance at 0x8755e>]
>>GetCachedVal()
start val: [<eDatabase instance at 0x87>, <eHandle instance at 0x8755e>]
>>print val
[<eDatabase instance at 0x87>, <eHandle instance at 0x8755e>]
t
More information about the Python-list
mailing list