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

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


Paul Bryan <pbryan at anode.ca> writes:

> On Wed, 2020-12-16 at 10:01 +0100, Loris Bennett wrote:
>
>> 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.
>
> But the function is still called. The get method just doesn't use (or
> return) the value it generates because the key exists. Nevertheless,
> you're passing the return value of the get_default function as an
> argument.
>
>> Thus, I am still unsurprised when dict.get returns the value of an
>> existing key.
>
> As am I.
>
>> What am I missing?
>
> You'll need to tell me at this point.

I was just slow and confused, but you helped me get there in the end.  I
now realise that issue is not about the result of the dict.get(), but
rather about the fact that the method which generates the default value
is called, whether or not it is needed.

I shall remember that next time I think it might be a good idea to
define a computationally massively expensive value as a rarely needed
default :-)

Cheers,

Loris

-- 
This signature is currently under construction.


More information about the Python-list mailing list