Needed: Real-world examples for Python's Cooperative Multiple Inheritance

John Nagle nagle at animats.com
Thu Nov 25 18:38:36 EST 2010


On 11/24/2010 12:08 PM, Raymond Hettinger wrote:
> I'm writing-up more guidance on how to use super() and would like to
> point at some real-world Python examples of cooperative multiple
> inheritance.
>
> Google searches take me to old papers for C++ and Eiffel, but that
> don't seem to be relevant to most Python programmers (i.e. a
> WalkingMenu example where a submenu is both a Entry in a Menu and a
> Menu itself).  Another published example is in a graphic library where
> some widgets inherit GraphicalFeature methods such as location, size
> and NestingGroupingFeatures such as finding parents, siblings, and
> children.  I don't find either of those examples compelling because
> there is no particular reason that they would have to have overlapping
> method names.
>
> So far, the only situation I can find where method names necessarily
> overlap is for the basics like __init__(), close(), flush(), and
> save() where multiple parents need to have their own initialization
> and finalization.
>
> If you guys know of good examples, I would appreciate a link or a
> recap.

    Multiple inheritance in Python is basically what fell out of
CPython's internals, not a design.  It's one of those areas where
order of execution matters, and that wasn't well worked out.
Allowing classes to form a directed acyclic graph isn't very
useful.  It just fell out of the semantics of a naive interpreter.

    Read "C3 method resolution order":

    http://www.python.org/download/releases/2.3/mro/

which is what you have to understand to use the awful cases properly.
Originally, the semantics were just wrong.  Now the awful cases
have well-defined semantics, but aren't very useful.

    Part of the problem is the notion that if a base class is duplicated
in the hierarchy, there's only one copy.  So if you inherit from two
classes, both of which inherit from "dict", there will be only one
"dict" at the bottom.  (I think.)  This probably won't do what the
authors of any of the classes involved expected.  The author
of the class which does the multiple inheritance might not even be
aware that there's a clash further up in the hierarchy.  This is
one of those areas where all the code looks right locally, but it's
wrong globally.

    Best practice for this is "don't do it."  Some name clashes ought
to simply be detected as errors, rather than being given such
complex semantics.

				John Nagle



More information about the Python-list mailing list