Setdefault bypasses __setitem__

Diez B. Roggisch deets at nospam.web.de
Thu Oct 13 20:26:22 EDT 2005


Duncan Booth wrote:
> Diez B. Roggisch wrote:
> 
> 
>>So if setdefault
>>was implemented as
>>
>>def setdefault(self, v):
>>     self["SOME_DEFAULT_KEY_NAME"] = v
> 
> 
> if setdefault was implemented that way then all current uses of setdefault 
> would throw an exception.
> 
> setdefault takes *three* parameters: self, key, value. Once you include the 
> key parameter your entire argument implodes.

Yup. It does implode, leaving me thunderstruck because of my dumbness.

I rarely find things in python strange or named incorrectly, but this is 
IMHO such a case - setdefault led me to think that using it would set a 
default value to return for _future_ lookups of non-existant keys. That 
semantics is known in e.g. ruby or java.

I think a better name would be getdefault, or even get_setdefault - in 
oppposition to the get(key, d) form.

But now that this became clear to me... I guess I can live with the name :)

Diez



More information about the Python-list mailing list