Advertisements

Diez B. Roggisch wrote:
> Ron Garret wrote:
>> Is this a bug or a feature?
>>
>> class mydict(dict):
>> def __setitem__(self, key, val):
>> print 'foo'
>> dict.__setitem__(self, key, val)
>>
>>
>>>>>d=mydict()
>>>>>d[1]=2
>>
>> foo
>>
>>>>>d.setdefault(2,3)
>
>
> Feature. If it wouldn't bypass __setitem__, how exactly would you make a
> default-item? Using __setitem__ implies a key. So if setdefault
> was implemented as
>
> def setdefault(self, v):
> self["SOME_DEFAULT_KEY_NAME"] = v
>
> and later on one writes e.g. a HTML-page with a form input field named
> "SOME_DEFAULT_KEY_NAME" that gets stored in a dict - it would overwrite
> the default value.
>
> So it has to bypass __setitem__, as otherwise it can't distinguish
> between "real" and the default value - the latter one is not allowed to
> have a key that is in any imaginable way used by the user.

The implementation is certainly a design decision. setdefault() could be
implemented in terms of __set/getitem__() as

Nope. What if you changed your default value? Then you'd have to update
the whole dictionary - but without keeping track of the keys you placed
the default value under that isn't possible. Which strikes me as
more-than-marginal overhead - without any advantage (as using
__setitem__ for the default value isn't something I consider being a
missing feature...)

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 B. Roggisch wrote:
> 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

Share This Page

Welcome to The Coding Forums!

Welcome to the Coding Forums, the place to chat about anything related to programming and coding languages.

Please join our friendly community by clicking the button below - it only takes a few seconds and is totally free. You'll be able to ask questions about coding or chat with the community and help others.
Sign up now!