Feature suggestion -- return if true

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Apr 17 17:23:18 CEST 2011

On Sun, 17 Apr 2011 19:07:03 +1000, Chris Angelico wrote:

> 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 you can create a sentinel value that is guaranteed to never appear 
anywhere else:

SENTINEL = object()
obj = cache.get(x, SENTINEL)
if obj is SENTINEL:
   obj = calculate(x)
   cache[x] = obj
return obj

You can create the sentinel once, at the start of your program, rather 
than each time.


More information about the Python-list mailing list