I don't understand the behavior of setdefault
in this scenario:
def f(x):
return x+1
dct = {5: 15}
print(dct.setdefault(5, f(5)))
The key 5 is in the dictionary, but instead of returning the value 15 immediately, it wastes time computing the function at the second argument. In the end, it discards the output of f
and returns 15.
Is this a bug? What is its purpose?