Delayed evaluation and setdefault()

Aahz aahz at
Mon Jan 19 20:52:17 CET 2004

In article <400C25FF.A76B1FEA at>,
Peter Hansen  <peter at> wrote:
>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]

First of all, Peter made a boo-boo in naming a parameter ``dict``.

If the key will be in the dict more than 90% (*very* roughly) of the time
you call this, you can do this instead:

def lazysetdefault(d, key, ref):
        return d[key]
    except KeyError:
        d[key] = ref()
        return d[key]

That minimizes the bytecode and function calls.
Aahz (aahz at           <*>

A: No.
Q: Is top-posting okay?

More information about the Python-list mailing list