I always assumed that the default value in the myDict.get('key', default_value)
expression was never called if the key exists in the dictionary. However, I have recently found out it somehow is. For example, consider the code
def doSomething():
print('Done')
return 'Another value'
myDict = {'key': 'value'}
print(myDict.get('key', doSomething()))
One would expect that since key exists in myDict, then the only thing myDict.get('key', doSomething())
would do is to return value and hence, the function doSomething would never be called. This is not the case however, and running this code in python currently outputs:
Done
value
My question is: why is this the case? Why isn't the default_value ignored completely when the key exists?
And what can be done to change this, that is, to not call the default_value when the key exists?