The addition of collections.defaultdict
in Python 2.5 greatly reduced the need for dict
's setdefault
method. This question is for our collective education:
- What is
setdefault
still useful for, today in Python 2.6/2.7? - What popular use cases of
setdefault
were superseded withcollections.defaultdict
?
As most answers state
setdefault
ordefaultdict
would let you set a default value when a key doesn't exist. However, I would like to point out a small caveat with regard to the use cases ofsetdefault
. When the Python interpreter executessetdefault
it will always evaluate the second argument to the function even if the key exists in the dictionary. For example:As you can see,
print
was also executed even though 2 already existed in the dictionary. This becomes particularly important if you are planning to usesetdefault
for example for an optimization likememoization
. If you add a recursive function call as the second argument tosetdefault
, you wouldn't get any performance out of it as Python would always be calling the function recursively.One very important use-case I just stumbled across:
dict.setdefault()
is great for multi-threaded code when you only want a single canonical object (as opposed to multiple objects that happen to be equal).For example, the
(Int)Flag
Enum in Python 3.6.0 has a bug: if multiple threads are competing for a composite(Int)Flag
member, there may end up being more than one:The solution is to use
setdefault()
as the last step of saving the computed composite member -- if another has already been saved then it is used instead of the new one, guaranteeing unique Enum members.Another use case that I don't think was mentioned above. Sometimes you keep a cache dict of objects by their id where primary instance is in the cache and you want to set cache when missing.
That's useful when you always want to keep a single instance per distinct id no matter how you obtain an obj each time. For example when object attributes get updated in memory and saving to storage is deferred.
I rewrote the accepted answer and facile it for the newbies.
Additionally,I categorized the methods as reference: