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

Paul Bryan pbryan at anode.ca
Wed Dec 16 03:41:53 EST 2020


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.

Paul



More information about the Python-list mailing list