[Python-ideas] dict(default=int)

Chris Angelico rosuav at gmail.com
Mon May 29 21:28:24 EDT 2017

On Tue, May 30, 2017 at 7:06 AM, Matt Gilson <matt at getpattern.com> wrote:
> On Mon, May 29, 2017 at 11:59 AM, Neil Girdhar <mistersheik at gmail.com>
> wrote:
>> A long time ago, I proposed that the dict variants (sorteddict,
>> defaultdict, weakkeydict, etc.) be made more discoverable by having them
>> specified as keyword arguments and I got the same feedback that the poster
>> here is getting.  Now, instead of moving these classes into dict, why not
>> have a factory like
>> dict.factory(values=None, *, ordered=True, sorted=False,
>> has_default=False, weak_keys=False, weak_values=False, …)
> Hmm ... I don't think that I like this.  For one, it greatly increases the
> amount of surface area that needs to be maintained in the standard library.
> As far as I know, we don't currently have a OrderedWeakKeyDictionary with
> defaultdict behavior.

"defaultdict behavior" can be tacked onto anything:

>>> class OrderedDefaultDict(collections.OrderedDict):
...     def __missing__(self, key):
...         self[key] = []
...         return self[key]

The core functionality of defaultdict is part of dict (the fact that
__missing__ gets called). The core functionality of weak references
could easily be added to dict too, if something like this were wanted.
So a lot of these would indeed be orthogonal. That said, though, I
don't know of many situations in which you would need an
OrderedWeakKeyDictionary, so if you have to write some custom code to
make that happen, so be it.


More information about the Python-ideas mailing list