dict.get(key, default) evaluates default even if key exists

dn PythonList at DancesWithMice.info
Tue Dec 15 18:01:01 EST 2020


 > On Tue, Dec 15, 2020 at 9:57 AM Mark Polesky via Python-list <
 > python-list at python.org> wrote:
 >
 >> 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.


Hey this is fun! A quick search reveals that I've (mea culpa) always 
thought of dict.get() as providing a default *value* and not used a 
function in there to provide said value.

That said, the function's name says it all: get_default(). Is it 
'getting' a default value? No, it's (also) reporting-back. Thus a 
"side-effect". Undesirable, as you say.

Were it appropriate to report that a default value was necessary, maybe 
something like:

     try:
         print( d[ 'a' ] )
     except KeyError:
         print( "Nobody expects this" )
         d[ 'a' ] = 0
-- 
Regards =dn


More information about the Python-list mailing list