Delayed evaluation and setdefault()
Aahz
aahz at pythoncraft.com
Mon Jan 19 14:52:17 EST 2004
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``.
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):
try:
return d[key]
except KeyError:
d[key] = ref()
return d[key]
That minimizes the bytecode and function calls.
--
Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/
A: No.
Q: Is top-posting okay?
More information about the Python-list
mailing list