Theoretically speaking, setdefault
would still be handy if you sometimes want to set a default and sometimes not. In real life, I haven't come across such a use case.
However, an interesting use case comes up from the standard library (Python 2.6, _threadinglocal.py):
>>> mydata = local()
>>> mydata.__dict__
{'number': 42}
>>> mydata.__dict__.setdefault('widgets', [])
[]
>>> mydata.widgets
[]
I would say that using __dict__.setdefault
is a pretty useful case.
Edit: As it happens, this is the only example in the standard library and it is in a comment. So may be it is not enough of a case to justify the existence of setdefault
. Still, here is an explanation:
Objects store their attributes in the __dict__
attribute. As it happens, the __dict__
attribute is writeable at any time after the object creation. It is also a dictionary not a defaultdict
. It is not sensible for objects in the general case to have __dict__
as a defaultdict
because that would make each object having all legal identifiers as attributes. So I can't foresee any change to Python objects getting rid of __dict__.setdefault
, apart from deleting it altogether if it was deemed not useful.