Why is __root checked for in OrderedDict?

A

andrew cooke

If you look at the code in
http://hg.python.org/cpython/file/6adbf5f3dafb/Lib/collections/__init__.py#l49 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.

My only guess is that this allows subclasses to do strange things without breaking the code (and if so, is a nice defensive coding pattern). But I am worried I am missing something.

Thanks,
Andrew
 
R

Raymond Hettinger

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:
{'a': 1, 'c': 5, 'b': 4}


Raymond
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,189
Latest member
CryptoTaxSoftware

Latest Threads

Top