On 19/05/2012 20:44, pete McEvoy wrote:
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?

The answer is yes.

someOtherFunct() is called and then 1 and the result of
someOtherFunct() are passed as arguments to myDict.setdefault(...).
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to