Setdefault bypasses __setitem__
Diez B. Roggisch
deets at nospam.web.de
Thu Oct 13 03:49:43 EDT 2005
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.
Diez
More information about the Python-list
mailing list