setdefault behaviour question

Chris Angelico rosuav at gmail.com
Sat May 19 19:49:25 EDT 2012


On Sun, May 20, 2012 at 5:44 AM, pete McEvoy <peterx.mcevoy at 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



More information about the Python-list mailing list