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

Chris Angelico rosuav at gmail.com
Wed Dec 16 04:44:11 EST 2020


On Wed, Dec 16, 2020 at 8:43 PM Loris Bennett
<loris.bennett at fu-berlin.de> wrote:
>
> 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 :-)
>

Yep! That's what defaultdict can do - or if you need more flexibility,
subclass dict and add a __missing__ method.

ChrisA


More information about the Python-list mailing list