Neil G
Neil G

Reputation: 33232

Why aren't Python dicts unified?

After reading this question, I noticed that S. Lott might have liked to use an “ordered defaultdict”, but it doesn't exist. Now, I wonder: Why do we have so many dict classes in Python?

Why not have something like this,

dict(initializer=[], sorted=False, ordered=False, default=None, 
     weak_keys=False, weak_values=False)

that unifies everything, and provides every useful combination?

Upvotes: 13

Views: 540

Answers (4)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798746

Those extra options don't come for free. Since 99.9% of Python is built on dict, it is very important to make it as minimal and fast as possible.

Upvotes: 8

S.Lott
S.Lott

Reputation: 391862

This is why languages have "mixins".

You could try to invent something like the following by defining the right bunch of classes.

class defaultdict( dict, unordered, default_init ): pass
class OrderedDict( dict, ordered, nodefault_init ): pass
class WeakKeyDict( dict, ordered, nodefault_init, weakkey ): pass
class KeyValueDict( dict, ordered, nodefault_init, weakvalue ): pass

Then, once you have those "unified" dictionaries, your applications look like this

groups= defaultdict( list )

No real change to the app, is there?

Upvotes: 0

FogleBird
FogleBird

Reputation: 76792

One issue is that making this change would break backward-compatibility, due to this type of constructor usage that exists now:

>>> dict(one=1, two=2)
{'two': 2, 'one': 1}

Upvotes: 12

phihag
phihag

Reputation: 287885

Because the implementations differ a lot. You'd basically end up with a dict factory that returns an instance of a _dict(A very fast, low-overhead dictionary - the current dict), ordereddict, defaultdict, ... class. Also, you could not initialize dictionaries with keyword arguments anymore; programs relying on this would fail:

>>> dict(sorted=42)
{'sorted': 42}
# Your proposal would lead to an empty dictionary here (breaking compatibility)

Besides, when it's reasonable, the various classes already inherit from each other:

>>> collections.defaultdict.__bases__
(<type 'dict'>,)

Upvotes: 4

Related Questions