Phillip J. Eby
pje at telecommunity.com
Tue Jan 20 10:05:41 EST 2004
At 02:41 PM 1/20/04 +0000, Moore, Paul wrote:
>From: Raymond Hettinger
> > [Bob Ippolito]
> >> d.setdefault(k, factory=list).append(v) ?
> > That is somewhat nice and backwards compatible too.
>How is it more expressive than d.setdefault(k, ).append(v)? As
>far as I can see, it's longer and contains an extra obscure(ish)
It's more expressive because it allows lazy evaluation: the list isn't
created unless a new one is needed. For lists, that's not such a big
deal. Indeed, it's entirely possible that the cost of adding the keyword
argument to the function call would outweigh the cost of creating and
discarding an emtpy list. But, when using a dictionary as a cache for an
expensive computation, this notation is much more compact than writing an
if-then or try-except block to do the same thing.
Even so, compactness is actually less the point than clarity. The factory
idiom is more readable (IMO) because it gets out of the way of the point of
the code. It says, "oh by the way, the default for new members of 'd' is
to be a new list, and now let's get on with what we're going to do with it."
More information about the Python-Dev