setdefault behaviour question

pete McEvoy peterx.mcevoy at gmail.com
Sat May 19 15:44:03 EDT 2012


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?



More information about the Python-list mailing list