setdefault behaviour question

P

pete McEvoy

I am confused by some of the dictionary setdefault behaviour, I think
I am probably missing the obvious here.

def someOtherFunct():
print "in someOtherFunct"
return 42

def someFunct():
myDict = {1: 2}
if myDict.has_key(1):
print "myDict has key 1"
x = myDict.setdefault(1, someOtherFunct()) # <<<<< I didn't
expect someOtherFunct to get called here
print "x", x
y = myDict.setdefault(5, someOtherFunct())
print "y", y


+++++++++++++++++++++

if I call someFunct() I get the following output

myDict has key 1
in someOtherFunct
x 2
in someOtherFunct
y 42


For the second use of setdefault I do expect a call as the dictionary
does not the key. Will the function, someOtherFunct, in setdefault
always be called anyway and it is just that the dictionary will not be
updated in any way?
 
P

pete McEvoy

Ah - I have checked some previous posts (sorry, should
have done this first) and I now can see that the
lazy style evaluation approach would not be good.
I can see the reasons it behaves this way.

many thanks anyway.
 

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

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top