Why does setdefault evaluate default when key is set?
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Unforgiving Himalayas Looping
--
Chapters
00:00 Question
00:58 Accepted answer (Score 10)
01:31 Thank you
--
Full question
https://stackoverflow.com/questions/2279...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #setdefault
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Unforgiving Himalayas Looping
--
Chapters
00:00 Question
00:58 Accepted answer (Score 10)
01:31 Thank you
--
Full question
https://stackoverflow.com/questions/2279...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #setdefault
#avk47
ACCEPTED ANSWER
Score 10
The problem is not in setdefault, but in a general principle in Python (as well as most languages) that all arguments must be evaluated before the function is called. That is, even before Python checks to see if the key is in the dictionary, it needs to know the value of both the key and the default value: and since the default value is the result of a function, that function must be called first.