Feature suggestion -- return if true

Gregory Ewing greg.ewing at canterbury.ac.nz
Sun Apr 17 00:21:53 EDT 2011


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.

-- 
Greg



More information about the Python-list mailing list