Delayed evaluation and setdefault()

Peter Hansen peter at engcorp.com
Tue Jan 20 11:46:00 EST 2004


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

Oops...  I was, uh, writing pseudo-code, not Python!  Yeah, that's it...

-but-at-least-it-would-have-executed-ly yr's,
 Peter



More information about the Python-list mailing list