Tricky Dictionary Question from newbie

Peter Hansen peter at engcorp.com
Tue Jul 12 15:29:18 CEST 2005


(Fixed top-posting)

James Carroll wrote:
 > On 7/11/05, Peter Hansen <peter at engcorp.com> wrote:
 >>(I always have to ignore the name to think about how it works, or it
 >>gets in the way of my understanding it.  The name makes fairly little
 >>sense to me.)

> Notice the dictionary is only changed if the key was missing.

James, I'll assume your reply was intended to address my comment above.

It's not so much that the concept of "set the default value for this 
key" is poorly captured by the name "setdefault", but that the function 
is used almost exclusively in the idiom below, where it is critical that 
it also _returns_ the value, which is usually then operated on 
immediately, usually in the same line of code.

dict.setdefault(key, defaultValue).someMethodOnKey()

or

dict.setdefault(key, defaultValue) #= value, where # is some operator.

I suppose I shouldn't blame setdefault() itself for being poorly named, 
but it's confusing to me each time I see it in the above, because the 
name doesn't emphasize that the value is being returned, and yet that 
fact is arguably more important than the fact that a default is set!

I can't think of a better name, though, although I might find "foo" less 
confusing in the above context. :-)

-Peter



More information about the Python-list mailing list