Why is __root checked for in OrderedDict?

Raymond Hettinger python at rcn.com
Thu Apr 7 15:30:04 EDT 2011

On Apr 7, 4:13 am, andrew cooke <and... at acooke.org> wrote:
> If you look at the code inhttp://hg.python.org/cpython/file/6adbf5f3dafb/Lib/collections/__init...the attribute __root is checked for, and only created if missing.  Why?
> I ask because, from what I understand, the __init__ method will only be called when the object is first being created, so __root will always be missing.

First of all, three cheers for reading the source code!

A user can call __init__() even after the OrderedDict instance has
already been created.  If so, the __root attribute will already exist
and the whole operation becomes equivalent to an update().

You can see the same behavior with regular dictionaries:

>>> d = dict(a=1, b=2)
>>> d.__init__(b=4, c=5)
>>> d
{'a': 1, 'c': 5, 'b': 4}


More information about the Python-list mailing list