开发者

Why aren't Python dicts unified?

开发者 https://www.devze.com 2023-03-18 17:49 出处:网络
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?

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?

  • dict
  • blist.sorteddict
  • collections.OrderedD开发者_如何学Goict
  • collections.defaultdict
  • weakref.WeakKeyDictionary
  • weakref.WeakValueDictionary
  • others?

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?


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}


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.


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'>,)


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消