Why is __root checked for in OrderedDict?

Raymond Hettinger python at rcn.com
Thu Apr 7 22:31:49 EDT 2011


On Apr 7, 2:40 pm, andrew cooke <and... at acooke.org> wrote:
> Is that normal?  I mean, OK, it's possible (and yes I forgot it could be called directly), but is there any usual reason to do so?

It's common for subclasses to call their parent's __init__ method, so
that should emulate dict as nearly as possible to help avoid
surprises.

For the most part, client code won't use __init__ directly because
update() already provides equivalent functionality (but with a better
name).

For list.__init__(), the behavior is different.  It clears the list,
so someone may be using an __init__ call when it isn't practical to
use the syntactic equivalents "del a[:]" or "a[:] = []".

Outside those cases, I don't it is "normal", but who knows what future
programmers will need to do?


> I guess what I'm asking is: if I'm writing library code should I be this careful?

For the standard library, it pays to really think out the corner cases
because you never know what people are going to rely on.  The Liskov
substitution principle asks us to make OrderedDict behave as much like
dict as possible (so that OD's can be used a drop-in substitute when
needed).

Also subclassers tend to stress the API in ways that wouldn't be
common for the base class.

For standard library code, I think all the little things matter:
* int(), bool(), list() etc all return a "zero"
  value when called with no arguments
* the ordered dict code internally calls __update()
  instead of update() so that a subclass can override
  update() without breaking the constructor
* eval(repr(obj)) should round-trip whereever possible
* containers should behave reasonable well even if someone
  makes the container reference itself:  a=[]; a.append(a)
* classes should try to be pickable, copyable, and deepcopyable, etc
 ...

Raymond



More information about the Python-list mailing list