Delayed evaluation and setdefault()

Peter Hansen peter at
Mon Jan 19 19:46:23 CET 2004

Leo Breebaart wrote:
>    >>> d.setdefault('foo', b())
> then b() *does* get executed regardless of whether or not the
> value it returns is actually used ('foo' was not found) or not
> ('foo' was found).
> So I guess my question is twofold: one, do people think
> differently, and if so why?; and two: is there any elegant (or
> other) way in which I can achieve the delayed evaluation I desire
> for setdefault, given a side-effect-having b()?

def lazysetdefault(dict, key, ref):
    if not dict.has_key(key):
        dict[key] = ref()
    return dict[key]

>>> d = {}
>>> lazysetdefault(d, 'foo', b)


More information about the Python-list mailing list