I'm trying to add a cache of sorts to an expensive function using a fixed dictionary. Something like this:
def func(arg):
if arg in precomputed:
return precomputed[arg]
else:
return expensive_function(arg)
Now it would be a bit cleaner if I could do something like this using dict.get()
default values:
def func(arg):
return precomputed.get(arg, expensive_function(arg))
The problem is, expensive_function()
runs regardless of whether precomputed.get()
succeeds, so we get all of the fat for none of the flavor.
Is there a way I can defer the call to expensive_function()
here so it is only called if precomputed_get()
fails?