modifying static (local) method variables

T

t scytale

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
start val: []
initializingstart val: []
initializing[<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
start val: []
initializing[<eDatabase instance at 0x87>, <eHandle instance at 0x8755e>]


t
 
S

Steve Holden

t said:
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?

Because an assignment to an argument inside the method merely rebinds
the local variable for the remainder of that execution. Mutating the
referenced object ensures that the changed value is available to further
calls.

regards
Steve
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top