On Sun, May 20, 2012 at 5:44 AM, pete McEvoy <peterx.mce...@gmail.com> wrote: > I am confused by some of the dictionary setdefault behaviour, I think > I am probably missing the obvious here. > > def someOtherFunct(): > print "in someOtherFunct" > return 42 > > x = myDict.setdefault(1, someOtherFunct()) # <<<<< I didn't > expect someOtherFunct to get called here
Python doesn't have lazy evaluation as such, but if what you want is a dictionary that calls a function of yours whenever a value isn't found, check out collections.defaultdict: >>> import collections >>> a=collections.defaultdict() >>> def func(): print("Generating a default!") return 42 >>> a.default_factory=func >>> x = a[1] Generating a default! >>> x = a[1] Tested in 3.2, but should work fine in 2.5 and newer. ChrisA -- http://mail.python.org/mailman/listinfo/python-list