[Python-3000] A request to keep dict.setdefault() in 3.0 (original) (raw)

Phillip J. Eby pje at telecommunity.com
Mon Jul 9 21:17:12 CEST 2007


At 07:59 PM 7/9/2007 +0100, tav wrote:

PEP 3100 suggests dict.setdefault() may be removed in Python 3, since it is in principle no longer necessary (due to the new defaultdict type).

However, there is another class of use cases which use setdefault for its limited atomic properties - the initialization of non-mutated data structures that are shared among threads. (And defaultdict cannot achieve the same thing.) +1 setdefault's ability to return current value is also a very useful functionality and has saved writing: if key not in dict: value = dict[key] = value with the simpler: value = dict.setdefault(key, ) Is there a better way to do the above without .setdefault?

Yes, in 2.5 there's collections.defaultdict. Of course, that only works if there is a fixed mapping from keys to initial computed values for the entire dictionary for all time. Oh, and if your code gets to create the dictionary. :)



More information about the Python-3000 mailing list