Raymond Hettinger python at rcn.com
Mon Apr 11 18:49:21 EDT 2011

On Apr 11, 2:35 pm, rantingrick <rantingr... at gmail.com> wrote:
> setdefault should take **kw args in the case of needing to set
> multiple defaults at one time. I would even settle for an *arg list if
> i had to. Anything is better than...
> d.setdefault(blah, blah)
> d.setdefault(blah, blah)
> d.setdefault(blah, blah)
> d.setdefault(blah, blah)
> if blah is not blah:
>     d.setdefault(blah, blah)

I hate to feed a troll, but I'm curious when you see that pattern of
calls.  The typical use case always makes immediate use of the value
returned by setdefault():

   d.setdefault(key, []).append()

The pattern you've shown would more typically be expressed like this:

   for key in multiple_defaults.items():
       if key, default_value not in d:
           d[key] = default_value

Or people sometimes use updates to get the same effect:

   result = multiple_defaults.copy()

Another approach is to use something like ChainMap() which has been
added to Python 3.3. http://docs.python.org/dev/library/collections.html#collections.ChainMap

   result = ChainMap(d, multiple_defaults)


More information about the Python-list mailing list