Multiple inheritance is GOOD

Last Update: 23.09.2009. By kerim in python

A long, long time ago someone told me that multiple inheritence is a very bad, bad thing.

Now suppose you have a class that has a set of attributes A and you have one that has a set of attributes B. A third class has A and B, a fourth has A and D, a fifth B and D. What happens if you have some tens of classes of that sort with an amount of perhaps 20 attribute sets and all that in the wildest possible combinations. Still with me? Well such a chaos is called SVG (here is a nice example) and for quite some time i was figuring out how to best arrage the python classes in order to keep redundant repetitions out of my codebase.

I had not realized how much the mantra of decade old teachings had infiltrated my thinking until by sheer desperation i entered “python multiple inheritance” into that “fraggin” google search box. And i learned that python does support multiple inheritance. With all the previous experiences concerning svg coding i thought i couldnt loose much trying it out and it turned out to be far better than i had feared (or “learned”) before.

Problems with multiple ineritance could be that you end up not knowing where a variable actually comes from if two or more of the classes that you extend happen to have the same members. Another fear I had was that perhaps the IDE would run into trouble with its autocomplete fucntions (you know … the nice things that make lazy programmers happy).

But after just reprogramming 80% of my svg library in one day, i think i can say that multiple inheritance is NOT “per se” bad. PyDev (which i use for programming) seems to get along rather well still with the classes. And when it comes to the question where which variable comes from Python helps you a bit though by simply taking the variable from the class that is defined first.

So a:

class myclass(A,B,C)....

where A and B and C define lets say a member “X” method, would result in the X of class A to be taken for myclass. A clear and good solution. I am not sure yet how documentation tools handle this, nor do i know if the mere fact that python takes the first definition of a variable or method really helps someone trying to understand the code (after all he doesnt know where the variable is initially placed). But given my experience with the initial problem i find this an interesting path to follow for a while.

:-) Man i must really have been frustrated to post about such a trivial discovery :-)

PS: pySVG +=0.1 is not far away. My worst problem at the moment is a naming conflict with some other guy who has the same name for his lib and not written anything for it for 4 years.