[Python-ideas] Is multiple inheritance Pythonic?

Andrew Barnert abarnert at yahoo.com
Fri Mar 18 16:59:53 EDT 2016


On Mar 18, 2016, at 11:11, Martin Teichmann <lkb.teichmann at gmail.com> wrote:
> 
> Or in the b) case, it should be easier to use multiple inheritance and
> mixins. I was thinking about a class algebra, so following the above
> example one could create a mixed class simply as
> MyProtocol = SSLMixin + HTTPProtocol.

That means you now have an anonymous class[1]--no name to show up in tracebacks or inspect, no way to jump to the class definition in IDEs, probably even no way to pickle instances unless you invent some new mechanism to make that work.

Also, this conflicts with the notion of type algebra from other languages: the sum of two or more types is like a tagged union.[2] Also, it's not much of an algebra if the only operation is (non-commutative) addition. What does MyMixin * YourMixin, or 2 * MyMixin mean?[3]

Also, + implies commutativity. That implication only goes so far (it's not true from string concatenation, obviously), but it's still going to flavor people's expectations.

And finally, what's the benefit over this:

    class MyProtocol(SSLMixin, HTTPProtocol): pass

Of course if you really want to do this, you can already just call the type function directly (although notice that even there, and even in the C API, you still have to pass some string in for the name...). Or, if you really want, create a metaclass that subclasses type and adds an __add__ method. (You could even write it as a "metaclass mixin"). But I think very little Pythonic code would want such a thing, so it's a bad idea to make it any easier than it is today.

From a larger point of view, I don't think there's any problem to be solved here. Your question is like asking whether we should get rid of (single) inheritance or delegation. They're both useful, in mostly different contexts--there's some overlap, and there are also cases where you should be using one but could instead abuse the other, but that doesn't mean either one is bad and needs to be declared unpythonic. It means that both are pythonic within their range and unpythonic outside it (and when your use falls into the overlap, you have to make a judgment call).

---


[1]: If you're thinking "but anonymous classes are good in Java", they're needed in Java to work around a problem Python has never had (how do you do closures in a language with no free functions?), and they're acceptable because nobody looks at the classes at runtime.

[2]: That is, an object that can act as either a MyMixin or a YourMixin (after you check which) but never both at the same time.

[3]: In other languages, these operations create product types--tuples or records.



More information about the Python-ideas mailing list