Feature suggestion -- return if true

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Apr 17 10:45:20 CEST 2011


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.

If the compute_from function is expensive (and it better be, otherwise 
why are you bothering with a cache?), that could be expensive:

compute_from = is_prime_number
get_from_cache(253590421923456781012937340348512751108342137327 *
               195789732345627381015532937340363481051277321451)

:)

A better way is to explicitly test for the sentinel:

    y = cache.get(x)
    if y is not None:
        ...




-- 
Steven



More information about the Python-list mailing list