Why is the default in dict.get(key[, default]) evaluated even if the key is in the dictionary?
>>> key = \'foo\'
>>> a={}
>>> b={k
As in any function call, the arguments are evaluated before the call is executed.
In this case dict.get()
is no exception...
Because you are evaluating it, then passing it as an argument to get
. This happens whether or not get
ends up using the argument.
To avoid the lookup you could:
value = b.get(key)
if value is None:
value = a[key]
Or if None
is allowed then:
not_set = object()
# ...
value = b.get(key, not_set)
if value is not_set:
value = a[key]
You can rewrite the example you gave as
b.get(key, a.get(key))
to avoid the exception. This will return None
if the key is in neither dictionary. More generally, if you want to avoid the evaluation of the second argument, you could use
try:
x = b[key]
except KeyError:
x = a[key] # or whatever the default value is supposed to be
a[key]
is a['foo']
and you don't have that key in a
.b.get
hence the errorb
is empty (but as the 2. points shows, this is not relevant)use this instead
x = b.get(key) or a.get(key)
or
and and
are short circuit operators, so if b
has the key it won't look at a
. But problems will arise if you have falsy
values in b
. If that is the case you can do:
x = b[key] if key in b else a.get(key)