[Python-Dev] lazy evaluation redux (was dict "setdefault". Feaure request or bugfix?)

Duncan Booth duncan@rcp.co.uk
Tue, 11 Feb 2003 15:12:55 +0000


Jesus Cea Avion <jcea@argo.es> wrote in news:3E49069B.FBD8FA@argo.es:

>> OK, you want "lazy evaluation", but only in a very specific case.
> 
> Specific but intuitive, useful and efficient, nevertheless.

One way to satisfy this would be to redefine setdefault something like 
this:

def setdefault(aDict, aKey, aValue=None, lazy=None):
   assert aValue is None or lazy is None
   if aKey not in aDict:
       aDict[aKey] = (if lazy is None: aValue else: lazy())
   return aDict[aKey]

Then your existing calls continue to work, but you have the option of 
specifying lazy evaluation, and the lazyness is clear at the point of call:

   myDict.setdefault(myKey, lazy=lambda:expensive_function(args))

No new syntax required (ignoring the gratuitous 'if' expression).
If this every gets implemented, sentinal values would be better than None, 
but I thought it better to keep the example simple.

I quite like Roman's idea for making lambda sometimes optional although

   myDict.setdefault(myKey, lazy=:expensive_function(args))

could be confused with := assignment in other languages.

-- 
Duncan Booth                                             duncan@rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?