Feature suggestion -- return if true

Chris Angelico rosuav at gmail.com
Sun Apr 17 05:07:03 EDT 2011

On Sun, Apr 17, 2011 at 6:45 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> On Sun, 17 Apr 2011 16:21:53 +1200, Gregory Ewing wrote:
>> Chris Angelico wrote:
>>> def fac(n):
>>>     # attempt to get from a cache
>>>     return? cache[n]
>>>     # not in cache, calculate the value
>>>     ret=1 if n<=1 else fac(n-1)*n
>>>     # and cache and return it
>>>     cache[n]=ret; return ret
>> My idiom for fetching from a cache looks like this:
>>    def get_from_cache(x):
>>      y = cache.get(x)
>>      if not y:
>>        y = compute_from(x)
>>        cache[x] = y
>>      return y
>> which doesn't require any conditional returns.
> I'm sure you realise that that snippet needlessly recalculates any cached
> result that happens to be false, but others reading might not.

Sure. In my (somewhat contrived) example of factorials, that's going
to be true (apart from 0! = 0); and if the function returns a string
or other object rather than an integer, same thing. If there's the
possibility of _ANY_ value coming back from the computation, then it
would need to be done as:

if x in cache: return cache[x]

or as:

  return cache[x]
except KeyError:
  # calculate etc

Obviously, as with everything, you need to know your own code and your own data.

Chris Angelico

More information about the Python-list mailing list