Setdefault bypasses __setitem__

Diez B. Roggisch deets at nospam.web.de
Thu Oct 13 11:54:00 CEST 2005


> 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...)

Diez



More information about the Python-list mailing list