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

Loris Bennett loris.bennett at fu-berlin.de
Wed Dec 16 04:01:21 EST 2020


Paul Bryan <pbryan at anode.ca> writes:

> On Wed, 2020-12-16 at 08:59 +0100, Loris Bennett wrote:
>
>> Isn't the second argument to D.get() the value to be return if the
>> first
>> argument is not a valid key?  In that case, why does it make any
>> difference here what the second argument of D.get() is since the key
>> 'a'
>> does exist?
>> 
>> Thus, I would indeed expect the code above to print '1'.  I am
>> obviously
>> missing something here.
>
> Yes, the second argument is what to return if there is no valid key.
> The second argument is evaluated before the call to the get function.
> It's return value is being supplied as an argument to the get function.
>
> Let's write a couple of quick functions to demonstrate...
>
>>>> def get(key, default):
> ...   print(f"{key=} {default=}")
> ... 
>>>> def generate_a_default_value():
> ...   return 1
> ... 
>>>> get("a", generate_a_default_value())
> key='a' default=1
>>>> 
>
> The generate_a_default_value function was called before the call to
> get. It was called so it could produce a value that is actually passed
> in as an argument to the get function.

OK, I get the point about when the default value is generated and that
potentially being surprising, but in the example originally given, the
key 'a' exists and has a value of '1', so the default value is not
needed.

Thus, I am still unsurprised when dict.get returns the value of an
existing key.

What am I missing?

Cheers,

Loris

-- 
This signature is currently under construction.


More information about the Python-list mailing list