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

Barry Warsaw barry at python.org
Mon Jul 9 21:35:50 CEST 2007


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On Jul 9, 2007, at 2:44 PM, Phillip J. Eby 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.)

Phillip, I support any initiative to keep .setdefault() or similar  
functionality.  When this thread came up before, I wasn't against  
defaultdict, I just didn't think it covered enough of the use cases  
of .setdefault() to warrant its removal.  You describe some  
additional use cases.

However, .setdefault() is a horrible name because it's not clear from  
the name that a 'get' operation also happens.

It occurs to me that I haven't reached my stupid idea quota for the  
day, so here goes.  What if we ditched .setdefault() as a name and  
gave .get() an optional argument to also set the key's value when  
it's missing.

class dict2(dict):
     """
     >>> d = dict2()
     >>> d.setdefault('foo', []).append(7)
     >>> sorted(d.items())
     [('foo', [7])]
     >>> d.setdefault('foo', []).append(8)
     >>> sorted(d.items())
     [('foo', [7, 8])]
     >>> d.get('bar', [], set_missing=True).append(9)
     >>> sorted(d.items())
     [('bar', [9]), ('foo', [7, 8])]
     >>> d.get('bar', [], True).append(10)
     >>> sorted(d.items())
     [('bar', [9, 10]), ('foo', [7, 8])]
     """
     def get(self, key, default=None, set_missing=False):
         missing = object()
         value = super(dict2, self).get(key, missing)
         if value is not missing:
             return value
         if set_missing:
             self[key] = default
         return default

This more or less conveys that both a get and a set operation is  
happening.  It also doesn't violate the rule against letting an  
argument change the return type of a function.  Maybe it will make  
this useful functionality more palatable.

Cheers,
- -Barry


-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.7 (Darwin)

iQCVAwUBRpKOGHEjvBPtnXfVAQJIxwP9Ev7aASfVOw3q1aiCZ3Pr4VsQwzmeb0SR
4xJR9VvAZVcsjL4wAaleU55vFir9fBnFkvEnMMRFOBJ49NtS6EuLt+yGkt22gadg
TSlfNK0t4oVeFT4MJ6AebaHwBL8PvILAbV5eJ6x3H0hH383rdcdtrRyFzvhKnBRy
tPqtjIZlU6Q=
=WxDp
-----END PGP SIGNATURE-----


More information about the Python-3000 mailing list