Consider the following code:
>>> def default_answer():
... print "Default was required!"
... return 100
...
>>> g = { 'name': 'Jordan', 'age': 35 }
>>> result = g.get('age', default_answer())
Default was required!
>>> result = g.pop('age', default_answer())
Default was required!
Notice that whether g
contains the expected key or not, default_answer is called. This makes sense programmatically but if default_answer
was computationally expensive this would be a hassle (to run a lot of code to create a value that was going to be thrown away).
The only way I can think of writing this without always calling default_answer
is:
result = g.pop('age', False) or default_answer()
Is this the best way to do it?
(Note that I'm aware that replacing default_answer
with an object with lazy evaluation would also solve part of this problem, but that's outside the scope of this question).
try: ... except:
off the table for some reason? – Saldanapop
for this instead ofget
? – Dominog
myself and am receiving it as an input... – Birthdefaultdict
always comes with the danger of hiding "real"KeyError
s. – Freakget
orpop
. You're looking for an idiom that works with either. – Dominoresult = g.get('age')
although it would work withresult = g['age']
. – Birth