Yes.  In order to call D.get( ) it needs to pass two arguments.  The first is 
'a', simple.  The second is the result of a call to get_default().   So, that 
is called.  From INSIDE get_default() it prints 'Nobody expects this' but you 
should expect it,  get_default() gets executed.   Following that it prints '1', 
because the default value was NOT USED.   If it was used, you would see 'Nobody 
expects this' followed by 0.

--- Joseph S.

-----Original Message-----
From: Mark Polesky <markpole...@yahoo.com> 
Sent: Tuesday, December 15, 2020 12:07 PM
To: python-list@python.org
Subject: dict.get(key, default) evaluates default even if key exists

Hi.

# Running this script....

D = {'a':1}
def get_default():
    print('Nobody expects this')
    return 0
print(D.get('a', get_default()))

# ...generates this output:

Nobody expects this
1

###

Since I'm brand new to this community, I thought I'd ask here first... Is this 
worthy of a bug report?  This behavior is definitely unexpected to me, and I 
accidentally coded an endless loop in a mutual recursion situation because of 
it.  Calling dict.get.__doc__ only gives this short sentence: Return the value 
for key if key is in the dictionary, else default.  Nothing in that docstring 
suggests that the default value is evaluated even if the key exists, and I 
can't think of any good reason to do so.

Am I missing something?

Thanks,
Mark

-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to