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

2020-12-15 Thread Mark Polesky via Python-list
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


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

2020-12-15 Thread Mark Polesky via Python-list
I see. Perhaps counterintuitive, but implemented consistently. Add it to the 
list of gotchas, I guess.

By the way... four helpful responses in under an hour, very impressive. Nice 
community here. Thanks to all who answered.

Mark






On Tuesday, December 15, 2020, 11:05:10 AM PST, Serhiy Storchaka 
 wrote: 





15.12.20 19:07, Mark Polesky via Python-list пише:

> # 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?


You are missed that expressions for function arguments are always
evaluated before passing their values to a function. This is expected
behavior, and I can't remember any programming language in which it's
different.

So dict.get() returns the value of argument default, which is computed
by calling function get_default() before calling dict.get().

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

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