Feature suggestion -- return if true

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


On 2011年4月17日 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.
-- 
Steven


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /