Setdefault bypasses __setitem__

Peter Otten __peter__ at
Thu Oct 13 12:56:32 CEST 2005

Diez B. Roggisch wrote:

>> The implementation is certainly a design decision. setdefault() could be
>> implemented in terms of __set/getitem__() as
>> def setdefault(self, key, value=None):
>>     try:
>>         return self[key]
>>     except KeyError:
>>         self[key] = value
>>         return self[key]
>> I guess it's not done for performance reasons.
> 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...)

Are we talking about the same setdefault()?

    D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D

There is no per-instance default value just on per call:

>>> d = {}
>>> d.setdefault("a", 1)
>>> d.setdefault("a", 42)

I'm sure there is a misunderstanding in our conversation, I'm just not able
to nail it...


More information about the Python-list mailing list