Looking at the source code, it seems the only "reason" is that OrderedDict
is written in Python, while defaultdict
is in C. But it seems this is changing as Python 3.5 should have a cOrderedDict (see Python Bugs), which highlights how bad my only explanation actually is.
Can anyone provide a better explanation? I hope there is a better reason.
Edit:
The alleged duplicate answer is OK for Python 2.7, not for Python 3 where the class/type distinction is gone. OrderedDict
and defaultdict
are both considered classes by the interpreter itself:
>>> collections.defaultdict
<class 'collections.defaultdict'>
>>> collections.OrderedDict
<class 'collections.OrderedDict'>
Based on what I can find on the python-dev archives, this is just a case of the devs not following their own guidelines.
Guido actually suggested renaming defaultdict
to DefaultDict
to fix this inconsistency during the discussion of the PEP that introduced OrderedDict
:
Anyway, it seems the collections module in particular is already internally inconsistent --
NamedTuple
vs.defaultdict
. In a sense defaultdict is the odd one out here, since these are things you import from some module, they're not built-in. Maybe it should be renamed toNamedDict
?
Note that NamedDict
is a typo, he meant DefaultDict
:
> I suppose you mean "DefaultDict".
Yes, I've been distracted. :-(
I'm not sure why this change (and similar changes for other modules, eg socket.socket
, datetime.datetime
) was never made, since Guido supported doing it.
Ironically, it was Guido (or maybe Alex Martelli) who came up with the name defaultdict
, despite the fact that they were basing it on an internal class Google was using called DefaultDict
:
Google has an internal data type called a
DefaultDict
which gets passed a default value upon construction. Its__getitem__
method, instead of raisingKeyError
, inserts a shallow copy (!) of the given default value into the dict when the value is not found....snip...
Over lunch with Alex Martelli, he proposed that a subclass of dict with this behavior (but implemented in C) would be a good addition to the language. It looks like it wouldn't be hard to implement. It could be a builtin named
defaultdict
. The first, required, argument to the constructor should be the default value. Remaining arguments (even keyword args) are passed unchanged to the dict constructor.
Discussion quickly moved from defaultdict
being a built-in to it being part of the collections
module, but the all-lowercase name stuck. This discussion took place back in 2006, so PEP 8 had been around for many years by then. Not sure why it never occurred to anyone that it should be named DefaultDict
at the time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With